Showing posts with label splat. Show all posts
Showing posts with label splat. Show all posts

Saturday, March 3, 2007

Splat!!

Oh the things you can learn by reading _why's code. It really is like being in the mind of a genius.

Over the past few days I've been playing around with the Camping “micro-framework.” Like Rails, Camping a web framework built on the MVC concept. While Rails aims to be feature rich, however, camping blazes off in the direction of keeping small and light weight. Oh, and did I mention exceedingly clever? Take the time to read through the source—the unabbridged version is better for this—there's lots of goodies in there.

Anyway. One of the cool tidbits in there is defining a to_a method for using with the splat operator. The splat "*" is used to explode an array into the parameter list of a method. For example, assume the following function:

def foo a,b
  puts "You gave me a(n) #{a}, and also a(n) #{b}.  How very generous of you!"
end

Normally the function would be called passing it two parameters:

foo "Apple", "Banana"

If you use the splat you can break up an array into the method:

fruit = %w|Kiwi Grape|
foo *fruit

Now, none of this is all too earth shattering; however, it does lead to some clever uses when paired with a suitable to_a class method.

class ContinentalBreakfast
  def initialize(*offerings)
    @offerings = offerings
  end
  def to_a # Pick some random fruit...
    plate = []
    table = @offerings.dup
    2.times do
      f = table[rand(table.length)]
      table.delete(f)
      plate << f
    end
    plate
  end
end

Cool. Now we can ask somebody to bring us back a bit of a snack:

foo *ContinentalBreakfast.new('grape','pear','melon','strawberry')

Pretty neat, eh?