Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Did Ruby ever support this?

Tags:

syntax

ruby

hash

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?

like image 873
TieDad Avatar asked Dec 20 '25 09:12

TieDad


2 Answers

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.

like image 152
Ryan Bigg Avatar answered Dec 22 '25 22:12

Ryan Bigg


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"}
like image 21
Yu Hao Avatar answered Dec 22 '25 21:12

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!