rubysyntaxhashruby-1.9

Ruby 1.9 hash with a dash in a key


In ruby 1.9 is there a way to define this hash with the new syntax?

irb> { a:  2 }
=> {:a=>2}

irb> { a-b:  2 }
SyntaxError: (irb):5: syntax error, unexpected tLABEL
{ a-b:  2 }
      ^

with the old one, it's working:

irb> { :"a-b" =>  2 }
=> {:"a-b"=>2}

Solution

  • As of Ruby 2.2, you also can use following syntax:

    {a: 1, b: 2, 'c-c': 3, d: 4}