Ruby On Rails Classroom image

Pooja  Negi / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2|
Lessons:- Hashes and Symbols

The second syntax replaces the symbol/hashrocket combination with the name of the key followed by a colon and a value:

{ name:  "Michael Hartl",  email:  "michael@example.com" }

This construction more closely follows the hash notation in other languages (such as JavaScript) and enjoys growing popularity in the Rails community. Both syntaxes are still in common use, so it’s essential to be able to recognize them. Most hashes in the rest of this book use the new notation, which won’t work with Ruby 1.8.7 or earlier; if you are using an earlier version of Ruby, you will either have to upgrade to Ruby 1.9 (recommended) or use the old hash notation.

                 Hash values can be virtually anything, even other hashes, as seen in Listing 4.6  

Listing 4.6 Nested hashes.

These sorts of hashes-of-hashes, or nested hashes, are heavily used by Rails, as we’ll see starting in Section 7.3.

               As with arrays and ranges, hashes respond to the each method. For example, consider a hash named flash with keys for two conditions, :success and :error:

 

>>  flash = { success:  "It worked!",  error:  "It failed." }
=>  {:success=> "It worked!",  :error=>  "It failed."}
>>  flash. each  do  |key,  value|
?>  puts  "Key #  {key.inspect}  has value #  {value.inspect}"
>>  end
Key :success has value "It worked!"
Key :error has value "It failed."

Note that, while the each method for arrays takes a block with only one variable, each for hashes takes two, a key and a value. Thus, the each method for a hash iterates
through the hash one key-value pair at a time. 

The last example uses the useful inspect method, which returns a string with a literal representation of the object it’s called on:

>>  puts   1..5).  to- a            # Put an array as a string.
1
2
3
4
5

>>  puts  (1..5).  to a.inspect          # Put a literal array.
[1,  2,  3,  4,  5]
>>  puts  :name,  :name.  inspect
name
:name
>> puts  "It worked!",  "It worked!" .inspect
It   worked!
"It  worked!"

 By the way, using inspect to print an object is common enough that there’s a shortcut for it, the p function:

>>  p   :name                  # Same as 'puts :name.inspect'
:name
 
 
 
image
Pooja   Negi

Skills    Ruby On Rails

Qualifications :- High School - SSN high school, College/University - HNBGU, College/University - SRHU,
Location :-Ranipokhari,Rishikesh,Uttarakhand,India
Description:- Student
Explore
 

  Students (0)