Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 740
Nathan Long Avatar asked Jun 09 '09 12:06

Nathan Long


People also ask

What are symbols in Ruby on Rails?

The :symbol , is as you mentioned it's an efficient way of representing names and strings; they are literal values. It is initialized and exists only once during the ruby session. It's not a string, since you don't have access to String methods; it's a Symbol. On top of that, it's immutable.

What is -> in Ruby?

-> == Dash Rocket Used to define a lambda literal in Ruby 1.9.

What are symbols used for in Ruby?

What's a Symbol in Ruby? A symbol is a unique instance of the Symbol class which is generally used for identifying a specific resource.

What is the difference between string and symbol in Ruby?

There are two main differences between String and Symbol in Ruby. String is mutable and Symbol is not: Because the String is mutable, it can be change in somewhere and can lead to the result is not correct. Symbol is immutable.


1 Answers

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.

like image 176
gbc Avatar answered Oct 08 '22 02:10

gbc