-1

Is there a difference between writing

parameter: "String"

and the lengthier

:parameter => "String"
sawa
  • 165,429
  • 45
  • 277
  • 381

4 Answers4

4

The first one does not work in Ruby 1.8

J-_-L
  • 9,079
  • 2
  • 40
  • 37
2

They both construct a hash key-value pair. For the most part they are interchangeable. The parameter: "String" syntax was introduced in Ruby 1.9 and is modeled after JSON.

There are some differences/gotchas. The biggest one is that the newer syntax doesn't handle quoted keys. In a 1.8-style hash, you can do this:

:"multi word key" => some_value

In a 1.9-style hash, this is a syntax error:

"multi word key": some_value
Jim Stewart
  • 16,964
  • 5
  • 69
  • 89
0

No difference.

I prefer 2nd syntax as I think it's easier to see when doing brief overview.

In Ruby 1.9.x and 2.0.0

graudeejs
  • 349
  • 1
  • 6
  • 1
    Incorrect, some symbols are only valid with the hashrocket syntax. You also **must** use the hashrocket if your Hash has non-symbol keys. – mu is too short Mar 24 '13 at 17:59
0

It's just a syntactic Sugar.

If you see in irb with Ruby 1.8.7

1.8.7 :004 > {:name => 'String'}
 => {:name=>"String"}

and With 1.9.3

1.9.3p392 :002 > {name: 'String'}
 => {:name=>"String"} 

Both return the same format.

AnkitG
  • 6,438
  • 7
  • 44
  • 72