franzejr / best-ruby

Ruby Tricks, Idiomatic Ruby, Refactoring and Best Practices
http://franzejr.github.io/best-ruby/
2.39k stars 218 forks source link

(head, *tail) #3

Closed ilyakava closed 9 years ago

ilyakava commented 9 years ago

I don't know if this is "tricky" enough but I thought this was cool

(head, *tail) = array # break off the first element of the array, and keep the rest separately

source

franzejr commented 9 years ago

Sure! Could you send a PR with this?! Thanks @ilyakava !

ch1c0t commented 9 years ago

What's more, we can leave off parentheses(if we would like to do so):

head, *tail = array
franzejr commented 9 years ago

Nice trick, could you guys send that via PR? What do you think?

0x0dea commented 9 years ago

How do you feel about using this monstrosity to demonstrate the generality of Ruby's destructuring semantics?

_,(_,_,((_,(foo,_)),_)) = [1, [2, [3, 4], [[5, [:target], 6], [7], 8, [9], 10]]]
foo # => :target
franzejr commented 9 years ago

Hey @0x0dea , I was thinking about your example. Why do you think it could be trick?

franzejr commented 9 years ago

More about this @ilyakava - http://devblog.avdi.org/2010/01/31/first-and-rest-in-ruby/