-2

To describe a hash for carrierwave configurations, I write like:

{
  provider: 'AWS',
  aws_access_key_id: ENV["aws_access_key_id"],
  aws_secret_access_key: ENV["aws_secret_access_key"],
}

However, tutorials seem the advice to write:

{
  :provider => 'AWS'
  :aws_access_key_id => ENV["aws_access_key_id"],
  :aws_secret_access_key => ENV["aws_secret_access_key"],
}

What is the difference between the two? Is there good reason to use one over the other?

Kimmo Hintikka
  • 13,472
  • 7
  • 34
  • 63
  • 1
    Your second question should be another... er.... question. – Wayne Conrad Feb 21 '16 at 12:09
  • As to your second question, `'a' == "a"` so there is no good reason (with the samples you provide). Please open a new question with proper examples and the error message if you want it answered proper – Nitz Feb 21 '16 at 18:42
  • deleted the second questions, I am not sure what it was but its not repeatable. I was thinking as well that 'a' == "a" that got me confused anyway it seems to work now so not sure what caused it. Maybe I was missing hyphen somewhere or my replace all " to ' did not work right for the page. – Kimmo Hintikka Feb 22 '16 at 09:26

3 Answers3

3

There is no difference.

nitz@comp:~$ irb
irb(main):001:0> {a:1}
=> {:a=>1}

This is a new syntax for specifying hashes with keys that are symbols, which is the "normal" way (as far as I can see) of defining hashes.
Also see What are the benefits of the new hash syntax in Ruby 1.9?

Community
  • 1
  • 1
Nitz
  • 320
  • 2
  • 9
1

This "JSON" syntax was added in ruby 1.9 http://effectif.com/ruby/update-your-project-for-ruby-19-hash-syntax

The only difference is that you can't do things like dashes with it:

:'foo-moo' => 2
mikej
  • 65,295
  • 17
  • 152
  • 131
antpaw
  • 15,444
  • 11
  • 59
  • 88
  • I'm not sure why you're calling this "'JSON' syntax," considering that in JSON all keys must be double-quoted (`{ foo: 1 }` is not valid JSON; `{ "foo": 1 }` is). – Jordan Running Feb 21 '16 at 19:23
1

It's the new syntax for ruby 1.9+, just a syntactic sugar, that's all.

http://breakthebit.org/post/8453341914/ruby-19-and-the-new-hash-syntax

I prefer to use the new as older syntax might get deprecated in near future.

Albert Paul
  • 1,168
  • 13
  • 23
  • 1
    The "old" syntax is definitely not going to get deprecated as it is still required if you use anything else than a Symbol as the key. For strings, integers or any other objects, you still need the "old" syntax. In fact, the serialization of `Hash#to_s` uses the "old" syntax only. – Holger Just Feb 21 '16 at 18:00