Marcel Molina just blew my mind with some Ruby syntactic sugar.
[*something]
is the same as
Array(something)
(Because we all know
something.to_a
is so last year.)
Seeing
session[:user_id] ||= authenticate_user
was what convinced me Ruby was going to replace Smalltalk as my favorite language, and of course
users.map(&:name).sort
is just prettier than
users.map { |u| u.name }.sort
Syntactic sugar can make coding so much sweeter.
Are there any other good bits of Ruby sugar I'm missing?
I've always been a fan of the power of Smalltalk, Python + Ruby's ability to catch unknown method calls, and turn them into actual functionality.
In ActiveRecords, this shows itself with our ability to make method calls like:
I love that!
http://video.google.com/videoplay?docid=8135690990081075324
this is some nice sugar
I've never seen syntax like 'users.map(&:name).sort' so i went to irb and typed '%w[asd xcv sdf wef].map(&:to_sym)' and it didn't work...
I haven't seen this particular trick before. Can you please explain how it works, or give a link to documentation? It's kind of a hard thing to Google for, and I can't find it in the Pickaxe.
@Will: I wrote something about it here: Symbol to Proc shorthand
@Golly: Try it in the Rails console, instead of vanilla irb. I think
Symbol#to_proc
is going to be in a future Ruby release, but for you need ActiveSupport to get it.What's the difference with [*something] ? [something] works for me. What does the 'splat' do exactly? Thanks
I'm not convinced that [*foo] is the same as Array(foo), try this:
Granted, it can be a useful distinction.
@Chronic: Wow, nice catch. I wonder if that's a bug, or if it's intentional they operate differently.