« Screencasting Ruby Metaprogramming | Main | Two New Metaprogramming Episodes »

June 16, 2008

Silly Ruby 1.9 trivia

  first, *, last = 1,2,3,4,5
  first  # => 1
  last   # => 5

TrackBack

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:

Comments

Cool:


>> first, *foo, last = 1,2,3,4,5
=> [1, 2, 3, 4, 5]
>> foo
=> [2, 3, 4]

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

def reverse(car, *cdr)
[*cdr] << car
end

(Untested)

The splat operator really is nice -- even in 1.8

car, *cdr = ["apple", "pear", "banana"]

car
=> "apple"
cdr
=> ['pear', 'banana']

Err.. meant something more like

def reverse(car, *cdr)
return [] if car == []
reverse(cdr) << car
end

but I kinda misunderstood how it works anyways. :\

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

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.

Working...

Post a comment

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now available
My Photo

Pragmatic Stuff

Photos

  • www.flickr.com
    This is a Flickr badge showing public photos from pragdave tagged with pragdave_badge. Make your own badge here.

Site Search

  • Google Search

    The web
    PragDave