new_hash = {:simon => "Talek", :lorem => "Ipsum"}
can be replaced by
new_hash = {simon: "Talek", lorem: "Ipsum"}
Is there also a shorter way of writing
:on => :collection
Applying the same logic raises an error:
on: :collection
Update to provide more info:
In my routes.rb:
get 'detail', { on: :member }
doesn't work. Neither does
get 'detail', on: :member
Error:
Exiting
SyntaxError: C:/Workspace/OE_11/CyberTrack_Rails3/config/routes.rb:23:
syntax error, unexpected ':'
get 'detail', { on: :member }
or
Exiting
SyntaxError: C:/Workspace/OE_11/CyberTrack_Rails3/config/routes.rb:23:
syntax error, unexpected ':'
get 'detail', on: :member
Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type.
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
This works just fine for me:
def get(*args) p *args end
get 'detail', on: :member
# "detail"
# { :on => :member }
RUBY_ENGINE
# => jruby
JRUBY_VERSION
# => 1.6.6
EDIT: Now that you provided the error message, it looks like you are not running Ruby 1.9. The new hash syntax was introduced in Ruby 1.9, it doesn't work in older versions. You need to make sure that you are running Ruby 1.9, either by verifying that you are running the right Ruby implementation (e.g. YARV supports 1.9, MRI doesn't) or, if you are running a Ruby implementation that supports multiple language versions (e.g. JRuby) that you are passing the correct command line flags (e.g. jruby --1.9
).
As others have mentioned, you need to use 1.9 to get this syntax to work. Setting the environment variable JRUBY_OPTS
to --1.9
will ensure you are using the right ruby version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With