Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Ruby 1.9 hash syntax

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
like image 776
Lieven Cardoen Avatar asked Mar 02 '12 14:03

Lieven Cardoen


People also ask

How do you write hash in Ruby?

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.

What is new hash Ruby?

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.

How do you access the hash in Ruby?

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.


2 Answers

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).

like image 112
Jörg W Mittag Avatar answered Oct 10 '22 04:10

Jörg W Mittag


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.

like image 22
Sébastien Le Callonnec Avatar answered Oct 10 '22 03:10

Sébastien Le Callonnec