When we define a dict/hash in Ruby, we do like this:
{:a => 'b'}
But I read some Ruby code like this:
{:a : 'b'}
This should be Python-like. Did any Ruby version support that? I didn't ever read any Ruby book mentioned that.
Update:
I ran the following command on a Linux box:
$ ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-linux]
$ ruby -e 'puts {a: "b"}'
-e:1: syntax error, unexpected ':', expecting '}'
puts {a: "b"}
^
And ran the following on my Macbook:
$ /Users/chaol/.rvm/wrappers/ruby-2.0.0-p247/ruby -v
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
$ /Users/chaol/.rvm/wrappers/ruby-2.0.0-p247/ruby -e 'puts {a: "b"}'
-e:1: syntax error, unexpected ':', expecting '}'
puts {a: "b"}
^
Both Ruby version are 1.9+, why do I still get the error?
The correct syntax in the second example is:
{ a: 'b' }
This is a new feature of Ruby 1.9 and beyond, allowing for a JSON-ish syntax to be used for Ruby hashes.
No, it's not supported in Ruby, but this similar syntax is supported since Ruby 1.9
h = { a: 'b' }
#=> {:a=>"b"}
it's equivalent to
h = { :a => 'b' }
#=> {:a=>"b"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With