Ruby sweetness

— April 19, 2006 at 13:52 PDT

Marcel Molina just blew my mind with some Ruby syntactic sugar.


is the same as


(Because we all know


is so last year.)


session[:user_id] ||= authenticate_user

was what convinced me Ruby was going to replace Smalltalk as my favorite language, and of course

is just prettier than { |u| }.sort

Syntactic sugar can make coding so much sweeter.

Are there any other good bits of Ruby sugar I'm missing?

9 comments — [none]

  1. Dr Nic2006-04-19 14:23:04

    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:

    p = Person.find_by_firstname_and_surname("Nic", "Williams")

    I love that!

  2. Kieran2006-04-19 23:47:28

    this is some nice sugar

  3. Golly2006-04-21 08:25:03

    I've never seen syntax like '' so i went to irb and typed '%w[asd xcv sdf wef].map(&:to_sym)' and it didn't work...

  4. Will2006-04-21 08:29:14

    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.

  5. Josh Susser2006-04-21 08:33:33

    @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.

  6. David North2006-04-21 11:31:34

    What's the difference with [*something] ? [something] works for me. What does the 'splat' do exactly? Thanks

  7. Josh Susser2006-04-21 13:30:07
    >> foo = [1, 2, 3]
    => [1, 2, 3]
    >> [foo]
    => [[1, 2, 3]]
    >> [*foo]
    => [1, 2, 3]
    >> bar = 3
    => 3
    >> [bar]
    => [3]
    >> [*bar]
    => [3]
  8. Chronic2006-05-10 23:03:22

    I'm not convinced that [*foo] is the same as Array(foo), try this:

    irb(main):012:0> a = nil
    => nil
    irb(main):013:0> Array(a)  
    => []
    irb(main):014:0> [*a]
    => [nil]

    Granted, it can be a useful distinction.

  9. Josh Susser2006-05-11 00:16:35

    @Chronic: Wow, nice catch. I wonder if that's a bug, or if it's intentional they operate differently.

Sorry, comments for this article are closed.