Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Params hash keys as symbols vs strings

<%= params[:action] %> 

and

<%= params['action'] %> 

display

index 

but what is the difference between this syntax?

like image 404
Vyacheslav Loginov Avatar asked Jun 21 '11 15:06

Vyacheslav Loginov


People also ask

What is the difference between string and symbol?

What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.

Why are symbols faster than strings?

Symbols are immutable; Strings aren't. Being immutable means that the values won't change. Therefore, Symbols are faster than Strings.

Is params a hash?

While params appears to be a hash, it is actually an instance of the ActionController::Parameters class.

How can you tell if a key is present in a hash?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.


1 Answers

In Rails, the params hash is actually a HashWithIndifferentAccess rather than a standard ruby Hash object. This allows you to use either strings like 'action' or symbols like :action to access the contents.

You will get the same results regardless of what you use, but keep in mind this only works on HashWithIndifferentAccess objects.

like image 66
Dylan Markow Avatar answered Sep 20 '22 23:09

Dylan Markow