Thursday, October 18, 2007

Ruby Hashes: Good Programming Habit

When you're making a hash in Ruby, you can add a trailing comma with no problems.


>> h = {:x => :y,}
=> {:x=>:y}

The benefit here is that you can then add subsequent key-value pairs without ever getting those lame "oops I forgot a comma" errors.


  1. Works with lists, too:

    >> foo = [1,2,]
    => [1, 2]

  2. Wha? I could have sworn I tried that at least once before and it didn't work. Good to know it does the right thing after all.

  3. Rubinius and JRuby are both bleeding-edge; if they lack the implementation, that's something to add.

    @piers - it **doesn't** work without the curly braces. so if you use Ruby's "invisible curly braces" then you can't use this trick. but if you are using curly braces it's a good habit to be in.

  4. Internet Explorer will hate you if you do the same with javascript.

  5. Internet Explorer seems filled with hate. At the minimum, it's definitely grumpy.


Note: Only a member of this blog may post a comment.