SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Sunday, March 22, 2009

Hash in ruby

Insert into Ruby Array


The following piece of code insert to each hash in the array a new element. I used destructive hash merge to add the new element to each hash in the array.

cities = [
{"Name" => "los angeles", "State" => "CA"},
{"Name" => "las vegas", "State" => "NV"},
{"Name" => "miami", "State" => "FL"}
]
cities.map! { |c| c.merge!("Count" => 1) }
puts cities

Iterate on Ruby hash (sorted and unsorted)


h = {”boy” => 1, “apple” => 2, “cat” => 3}
h.each {|key, value| puts "#{key} => #{value}"}

Will output:
cat => 3
boy => 1
apple => 2

Getting Value from Hash


inst_section = {
:cello => 'string',
:clarinet => 'woodwind',
:drum => 'percussion',
:oboe => 'woodwind',
:trumpet => 'brass',
:violin => 'string'
}

inst_section[:trumpet] produces the output brass

No comments :

Post a Comment