Hashes in Ruby

Create a hash:

dictionary = { ‘cat’ => ‘feline animal’, ‘dog’ => ‘canine animal’ }

1. puts dictionary.size

output: 2
2. puts dictionary[‘cat’]

output: feline animal

3. dictionary[‘cat’] = “fluffy animal”
puts dictionary[‘cat’]

output: fluffy animal

Basic Hash Methods

Iterating Through Hash Elements

x = { “a” => 1, “b” => 2 }
x.each { |key, value| puts “#{key} equals #{value}” }
output:

a equals 1
b equals 2

Retrieving Keys

x = { “a” => 1, “b” => 2, “c” => 3 }
puts x.keys.inspect
output:

[“a”, “b”, “c”]

Deleting Hash Elements

x = { “a” => 1, “b” => 2 }
x.delete(“a”)
puts x.inspect

output:

{“b”=>2}

Deleting Hash Elements Conditionally

x = { “a” => 100, “b” => 20 }
x.delete_if { |key, value| value < 25 }
puts x.inspect
output:

{“a”=>100}

Hashes Within Hashes

people = {
‘fred’ => {
‘name’ => ‘Fred Elliott’,
‘age’ => 63,
‘gender’ => ‘male’,
‘favorite painters’ => [‘Monet’, ‘Constable’, ‘Da Vinci’]
},
‘janet’ => {
‘name’ => ‘Janet S Porter’,’age’ => 55,
‘gender’ => ‘female’
}
}
puts people[‘fred’][‘age’]
puts people[‘janet’][‘gender’]
puts people[‘janet’].inspect

output:

63
female
{“name”=>”Janet S Porter”, “gender”=>”female”, “age”=>55}

puts people[‘fred’][‘favorite painters’].length
puts people[‘fred’][‘favorite painters’].join(“, “)
output:

3
Monet, Constable, Da Vinci

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s