Hash Flashcards
How to calculate count of array items with Hash?
hash = Hash.new(0)
array_of_values.each do |value|
hash[value] += 1
end
How to merge 2 hashes and select the biggest value?
The block is invoked only to solve conflicts, when a key is present in both hashes.
a = {“n”=>3, “a”=>3, “g”=>2}
b = {“n”=>3, “a”=>3, “g”=>100}
a.merge!(b) { |key, value_a, value_b| [value_a, value_b].max }
How to update hash values? 3 ways
1) { :a=>’a’ , :b=>’b’ }.transform_values! { |v| “#{v}” }
2) { a: ‘a’, b: ‘b’ }.map { |k, value| [k, “#{value}”] }.to_h
3) my_hash.each{ |key,value| my_hash[key] = “#{value}” }
What type of keys we can use for hash?
Any object
a = {1 => ‘dd’, :a => 2, “a” => 3, true => 4, nil => 5}
p a[1]
p a[:a]
p a[“a”]
p a[true]
p a[nil]
How to make hash hey argument unnecessary?
Set default value
def hello(name:, nic: nil)
p nic
end
hello(name: 213)
What is the correct way to initialize default hash value with array?
hash = Hash.new { |hash, key| [] }
p hash[‘d’] «_space;‘d’
p hash[‘v’]
# [“d”]
# []
How to iterate only by hash values?
h = { “a” => 100, “b” => 200 }
h.each_value {|value| puts value }
# => 100
# => 200
How to convert array of object to single hash?
Model.all.to_h { [_1.name, _1.id] }
{“identity”=>1, “address”=>2 }