简体   繁体   中英

Ruby on Rails: what does the => symbol mean?

I am working my way through Head First Rails, and I keep seeing => . It's in the routes:

map.connect '/marmots/new', controller=>'marmots', :action=>'new'

It's in rendering partials:

render :partial=>"new_marmot"

It's in options for links:

<%= link_to 'Destroy', marmot, :confirm=>'Are you sure?', :method=>:delete %>

Basically, => seems to mean 'equals,' but if so, why not just use an equals sign? Is it more like 'send to?'

How do you pronounce => and what do you understand it to mean? I can get by without knowing this, but it bugs me.

I've heard it commonly referred to as a "hash rocket". It is the assignment operator used with hashes in ruby. So if you have a hash and want to assign a value to a key (typically a literal), use

{key1 => value1, key2 => value2}

Rails, and other Ruby code, often pass hashes as parameters to methods to achieve the same effect as named arguments in other languages like Python.

object.method({:param1 => value1, :param2 => value2})

EDIT: When reading, I use "gets" as the verb, eg. param1 gets value1, etc.

Your first function call is a shortcut for

map.connect('/marmots/new', {:controller=>'marmots', :action=>'new'})

where the {} are a Hash-literal. The second argument of the method connect of the object map is an object of class Hash with the two keys :controller and :action (both are literals of the class Symbol) whose corresponding values are the two strings 'marmots' and 'new'.

EDIT: I call it "arrow" or "maps to".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM