Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map_values() for Ruby hashes?

Tags:

ruby

hash

I miss a Hash method in Ruby to transform/map only the values of the hash.

h = { 1 => [9,2,3,4], 2 => [6], 3 => [5,7,1] }
h.map_values { |v| v.size }
#=> { 1 => 4, 2 => 1, 3 => 3 } 

How do you archive this in Ruby?

Update: I'm looking for an implementation of map_values().

# more examples
h.map_values { |v| v.reduce(0, :+) }
#=> { 1 => 18, 2 => 6, 3 => 13 } 

h.map_values(&:min)
#=> { 1 => 2, 2 => 6, 3 => 1 }
like image 904
sschmeck Avatar asked Dec 14 '15 10:12

sschmeck


People also ask

How do you access hashes in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do you check if something is a hash Ruby?

A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .

How do you know if two hashes are equal Ruby?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared. Returns true if other is subset of hash.


1 Answers

Ruby 2.4 introduced the methods Hash#transform_values and Hash#transform_values! with the desired behavoir.

h = { 1=>[9, 2, 3, 4], 2=>[6], 3=>[5, 7, 1] }
h.transform_values { |e| e.size }
#=> {1=>4, 2=>1, 3=>3}
like image 59
sschmeck Avatar answered Nov 10 '22 12:11

sschmeck