Silly Ruby 1.9 trivia
first, *, last = 1,2,3,4,5
first # => 1
last # => 5
« Screencasting Ruby Metaprogramming | Main | Two New Metaprogramming Episodes »
first, *, last = 1,2,3,4,5
first # => 1
last # => 5
TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451c41c69e200e553584b998833
Listed below are links to weblogs that reference Silly Ruby 1.9 trivia:
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
Cool:
>> first, *foo, last = 1,2,3,4,5
=> [1, 2, 3, 4, 5]
>> foo
=> [2, 3, 4]
Posted by: Dr Nic | June 16, 2008 at 10:32 PM
Nic:
Works for methods, too...
irb(main):001:0> def fred(first, *, last)
irb(main):002:1> p first, last
irb(main):003:1> end
=> nil
irb(main):004:0> fred(1,2,3,4,5)
1
5
Posted by: Dave Thomas | June 17, 2008 at 01:23 AM
def reverse(car, *cdr)
[*cdr] << car
end
(Untested)
Posted by: Brennan | June 17, 2008 at 08:57 AM
The splat operator really is nice -- even in 1.8
car, *cdr = ["apple", "pear", "banana"]
car
=> "apple"
cdr
=> ['pear', 'banana']
Posted by: James Whiteman | June 17, 2008 at 09:56 AM
Err.. meant something more like
def reverse(car, *cdr)
return [] if car == []
reverse(cdr) << car
end
but I kinda misunderstood how it works anyways. :\
Posted by: Brennan | June 17, 2008 at 12:43 PM