3 ms·
Correct. It is wonderful sugar, but somewhat limiting. Realistically, you need to know both syntaxes. irb(main):001:0> hash={:"symbol with space" => nil}
by laymil 16y ago
Correct. It is wonderful sugar, but somewhat limiting. Realistically, you need to know both syntaxes.
irb(main):001:0> hash={:"symbol with space" => nil}
=> {:"symbol with space"=>nil}
irb(main):002:0> hash={"symbol with space": nil}
SyntaxError: (irb):2: syntax error, unexpected ':', expecting tASSOC
hash={"symbol with space": nil}
^
from /usr/bin/irb1.9.1:12:in `<main>'
irb(main):003:0> hash={"symbolwithoutspace": nil}
SyntaxError: (irb):3: syntax error, unexpected ':', expecting tASSOC
hash={"symbolwithoutspace": nil}
^
from /usr/bin/irb1.9.1:12:in `<main>'
irb(main):004:0> hash={symbolwithoutspace: nil}
=> {:symbolwithoutspace=>nil}
irb(main):005:0> hash={symbol with space: nil}
SyntaxError: (irb):5: syntax error, unexpected tIDENTIFIER, expecting keyword_do or '{' or '('
hash={symbol with space: nil}
- cubicle67 16y agoMy own opinion is that although Ruby allows string-like symbols (like :"symbol with space"), I think they should be avoided. There may be a case for them, but I've not encountered one yet. The new syntax works only with conventional symbols (no quotes), not with any other key type, so no integers, strings, objects etc. For everything else, you can fall back to the original syntax. You can even mix then if you really feel the need (yech!) That said, for almost all use cases hashes use symbols as keys, and for these cases the new syntax is much cleaner and I'm glad to see it
- aaronbrethorst 16y agoCombining Haml with jQuery Mobile makes it pretty much mandatory: #main_page{:"data-role" => 'page'}
- nex3 16y agoHaml keys can be plain strings. #main_page{"data-role" => 'page'} `data-` attributes are also special-cased: #main_page{data: {role: 'page'}}
- aaronbrethorst 16y agoI did not know that. Thanks for the heads up, and thanks for Haml and Sass!
- snprbob86 16y agoYou can also use "HTML-style attributes" [1] #main_page(data-role='page') [1] http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#htmlstyle_attributes_ http://haml-lang.com/docs/yardoc/file.HAML_REFERENCE.html#ht...
- ericb 16y ago> That said, for almost all use cases hashes use symbols as keys I'd say there are more vanilla symbol hash uses by number, but the most interesting and powerful things you can do with hashes don't involve symbols for keys, imho.