Ruby Hash

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


Ruby hashes are equivalent to Java Hashmaps and allows us to store information as key-value pair in contrast to arrays in which we can have only integer keys or indices. Thus, Ruby hashes are generalization of arrays.

Ruby Hash Example

#!/usr/bin/ruby
# File: rubyhash.rb
 
address = {
	"First name" => "Anthony",
	"Last name"  => "Moody",
	"Street"    => "101 LA Street",  
	"City"       => "CA",
	"Country"   => "US"
}
 
puts address['City']

Output of the above code would be CA.

Ruby Hashes Iteration through Foreach

#!/usr/bin/ruby
# File: rubyhashforeach.rb
 
address.each do |key, value| 
	puts key + " - " + value 
end

This would output:

	"First name" - "Anthony",
	"Last name"  - "Moody",
	"Street"     - "101 LA Street",  
	"City"       - "CA",
	"Country"    - "US"

Having learnt Ruby arrays and hash, now learn how to convert Ruby arrays to hashes.





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.