Hash Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

How to calculate count of array items with Hash?

A

hash = Hash.new(0)
array_of_values.each do |value|
hash[value] += 1
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to merge 2 hashes and select the biggest value?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to update hash values? 3 ways

A

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}” }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What type of keys we can use for hash?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to make hash hey argument unnecessary?

A

Set default value

def hello(name:, nic: nil)
p nic
end

hello(name: 213)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the correct way to initialize default hash value with array?

A

hash = Hash.new { |hash, key| [] }

p hash[‘d’] &laquo_space;‘d’
p hash[‘v’]
# [“d”]
# []

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to iterate only by hash values?

A

h = { “a” => 100, “b” => 200 }
h.each_value {|value| puts value }
# => 100
# => 200

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to convert array of object to single hash?

A

Model.all.to_h { [_1.name, _1.id] }

{“identity”=>1, “address”=>2 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly