View Category

Define an empty map

ruby
map = {}

Define an unmodifiable empty map

ruby
map = {}.freeze

Define an initial map

Define the map {circle:1, triangle:3, square:4}
ruby
shapes = {'circle'=>1, 'triangle'=>3, 'square'=>4}
shapes = Hash['circle', 1, 'triangle', 3, 'square', 4]
shapes = { :circle => 1, :triangle => 3, :square => 4 }

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
ruby
puts "ok" if map.has_key?('mary')
puts "ok" if map['mary'] # Only works if map entry can't be nil or false

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
ruby
puts map['joe']

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
ruby
pets['rob']='dog'

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
ruby
puts map.delete :bill

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
ruby
histogram = {}
list.each { |item| histogram[item] = (histogram[item] || 0) +1 }
list = %w{a b a c b b}

histogram = list.each_with_object(Hash.new(0)) do |item, hash|
hash[item] += 1
end

p histogram # => {"a"=>2, "b"=>3, "c"=>1}
list.inject(Hash.new(0)) {|h, item| h[item] += 1; h}

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
ruby
lengths = {}
list.each do |x|
len = x.size
lengths[len] = (lengths[len] || [])
lengths[len] << x
end
lengths = list.group_by {|x| x.size}
list.inject({}) { |h,x| (h[x.size]||=[]) << x; h }