Ruby Hashes In Depth
A hash maps keys to values. Symbol keys use a: 1 syntax. Methods: fetch, dig, key?, keys, values, merge, select, transform_values, to_a and default values.
Example
h = { name: "Ada", age: 21 }
puts h[:name], h.fetch(:age), h.key?(:x)
h[:city] = "Lagos"
puts h.keys.inspect
puts h.merge(age: 22).inspect
puts h.transform_values(&:to_s).inspect
count = Hash.new(0)
"hello".each_char { |c| count[c] += 1 }
puts count.inspect
puts({ a: { b: 1 } }.dig(:a, :b))Result
Ada
21
false
[:name, :age, :city]
{:name=>"Ada", :age=>22, :city=>"Lagos"}
{:name=>"Ada", :age=>"21", :city=>"Lagos"}
{"h"=>1, "e"=>1, "l"=>2, "o"=>1}
1Exercise
Default for missing keys.
Hash.new()
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.