0

I am not sure if I can ask about programming conventions on stackoverflow, but since my goal is to be better at programming coding and stylistically, I guess it cannot hurt.

I would like to know what is the best style to write a hash in ruby I have seen

a = {a: 'a', b: 'b'}    

b = { a: 'a', b: 'b' }

c = {:a=>'a', :b=>'b'}

d = {:a => 'a', :b => 'b'}

e = { :a => 'a', :b => 'b' }

I prefer the first because it matches arrays [a, b, c] or param('a', 'b') but I have seen tutorials using the second style.

I know there might be personal preference but I want to know the convention like 'tabs should be two spaces instead of four'. I know the hash rocket is older syntax, lets assume I'm using the newest rails and ruby verions.

2
  • The hashrocket is not older syntax, how would you { a => 'a' } or { :$set => { ... } } with the JavaScript-style notation? Nov 25, 2013 at 22:53
  • This question mixes technical and esthetic style. Prefer a:, unless you must use a key which is not a symbol that obeys Ruby identifier rules; 'key' =>. And the latter IS "old-style" because it was formerly the only kind of hash available.
    – Phlip
    Nov 25, 2013 at 23:09

2 Answers 2

3

From the Ruby Style Guide

# good - space after { and before }
{ one: 1, two: 2 }

# good - no space after { and before }
{one: 1, two: 2}

I personally favor

a = {a: 'a', b: 'b'}

The => are part of the old <= 1.8 hash syntax


Note, when using hashes in method calls, you can omit the {}

some_method a: 'a', b: 'b'
2
  • And when it needs to have a numeric key?
    – vgoff
    Nov 26, 2013 at 0:56
  • when you have a numeric key then you can revert to a hash rocket but for symbols i would use this, or use an array for numeric key. Nov 26, 2013 at 4:18
0

This is totally an opinion question, but my opinion answer is "B" above... It's easiest to read and is the newest "standard" for hashes. That said, there's nothing wrong with "A", but I think the extra spaces makes it easier to read.

Full disclosure, I still prefer "E" - I've never gotten away from hashrockets... But I'm old school like that.

1
  • 1
    Also, the "old style" is required for those things that can't use the newer "colon appended" style. So it isn't always opinion, in some cases the opinion doesn't matter as much as what is technically allowed.
    – vgoff
    Nov 26, 2013 at 0:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.