English 中文(简体)
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}
最佳回答

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

{a: 1, b: 2,  c-c : 3, d: 4}
问题回答

There are some legitimate symbols that cannot be used with the new syntax. I cannot find a reference, but it appears that a symbol name matching /^[a-zA-Z_][a-zA-Z_0-9]*[!?]?$/ is allowed with the new syntax. The last character may be the special character "!" or "?".

For any symbol that does not meet these restrictions, you have to use the Ruby 1.8 syntax, : my-symbol-name

You can combine the old and new syntax:

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

To use dashes with the new syntax:

<%= link_to "Link", link_path, {data: {something:  value1 , somethingelse:  value2 }} %>

This will generate:

<a href="/link" data-something= value1  data-somethingelse= value2 >Link</a>

This might not exactly be your particular use case, but I found this post while trying to find an answer myself so I thought I d share my findings.





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签