As you probably know, the colon (key: value
) syntax was introduced in Ruby 1.9. If you're writing a library that you're going to distribute to people who might be running an earlier version of Ruby, use the arrow (:key => value
) syntax.
Other than that, it's really up to personal preference. I prefer the colon syntax because it generally reduces visual clutter, by virtue of having one less symbol on the screen, without reducing readability.
One scenario I prefer the arrow syntax for, though, is in DSLs where a hash's arrow syntax is being used (or, it could be argued, abused) to represent a "from X to Y" relationship. A good example is the state_machine gem, which describes transitions like this:
transition :first_gear => :idling
Here the arrow makes it this read almost like English: "On idle, objects in the first gear state should transition to idling." It wouldn't be illegible with the colon syntax, but because state_machine also allows arrays as keys, it's good to use arrow syntax anyway just for consistency:
transition first_gear: :idling
# ...
transition [:idling, :first_gear] => :parked
Here they don't match, and it's a visually and mentally jarring—not much, but enough to be worth consideration.
I also sometimes prefer it in Rails when doing ActiveRecord queries through associations, e.g.
User.where( active: true, :role => { name: "admin" } )
# vs.
User.where( active: true, role: { name: "admin" } )
For some reason the =>
helps reinforce my understanding of the association or the JOIN. Once again, merely a personal preference, and in this case I think it makes even less of a difference than in the state_machine example.