airbnb / ruby

Ruby Style Guide

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hash symbol key style is unclear

spikebrehm opened this issue · comments

In the Collections section, we have this example:

# bad
hash = { 'one' => 1, 'two' => 2, 'three' => 3 }

# good
hash = { one: 1, two: 2, three: 3 }

The point of this example is to show using symbols as keys instead of strings. This would be a more clear example as:

# bad
hash = { 'one' => 1, 'two' => 2, 'three' => 3 }

# good
hash = { :one => 1, :two => 2, :three => 3 }

Also, the style guide doesn't seem to comment on the preferred style of symbol keys; the Ruby <= 1.8 style vs the Ruby >= 1.9 style:

# bad/good???
hash = { :one => 1, :two => 2, :three => 3 }

# bad/good???
hash = { one: 1, two: 2, three: 3 }

I agree that the style guide is unclear on the preferred style.

Just adding the fact that @bbatsov ruby style guide prefers Ruby 1.9 style https://github.com/bbatsov/ruby-style-guide#hash-literals.

I updated the guide to use Ruby 1.8 style. While the 1.9 style is nice and may be in wider use now, we should keep the 1.8 style for Airbnb specifically. Large parts of our codebase were written prior to the advent of Ruby 1.9, so the 1.8 style appears all over the place. We should just stay consistent instead of mixing styles and making things confusing.

Another reason to prefer the 1.8 style is that the 1.9 style only works when the keys are symbols. There are many cases when you might need to define a hash literal with non-symbol keys, so you'll have to use the 1.8 syntax sometimes anyway. At that point, you may as well just use one style consistently. (This is just my personal belief though, expressed here for the sake of conversation, and not related to why I updated the style guide to specify the 1.8 style.)

@clizzin thanks for the reactivity. Given your comment it makes totally sense for Airbnb to choose that version.

For the sake of conversation:
I do prefer the other 1.9 style, it saves 3 chars each times it is used (so that makes 9 on the example above), which makes a more compact but still very readable code.
Plus most of the time keys are Symbols (I find it not that bad to have once a while a hash with string key using 1.8 style, given that the hash itself is consistent (https://github.com/bbatsov/ruby-style-guide#no-mixed-hash-syntaces))
Finally that makes the code more similar to Javascript or even Python, which I kind of like. (entirely a personal opinion)

Anyway thanks for settling and closing.