map_values() for Ruby hashes? - ruby

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 }

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}

You can monkey-patch the hash class, like this
class Hash
def map_values
map { |k, v|
[k, yield(v)]
}.to_h
end
end
p ({1 => [1,1,1,1], 2 => [2], 3 => [3,3,3]}.map_values { |e| e.size })

You can also use Hash#update for this:
h = { 1 => [9, 2, 3, 4], 2 => [6], 3 => [5, 7, 1] }
h.update(h) { |_, v| v.size }
#=> { 1 => 4, 2 => 1, 3 => 3 }
It replaces all values that have duplicate keys in one hash with that of another, or, if a block is given, with the result of calling the block. You can pass the original hash as the argument to ensure all values are replaced.
Note that this modifies the hash in place! If you want to preserve the original hash, dup it first:
h.dup.update(h) { |_, v| v.size }
#=> { 1 => 4, 2 => 1, 3 => 3 }
h
#=> { 1 => [9, 2, 3, 4], 2 => [6], 3 => [5, 7, 1] }

This will do the trick for you
h = { 1 => [1,1,1,1], 2 => [2], 3 => [3,3,3] }
h.map {|k,v| [k, v.size] }.to_h

No map, just each
h = { 1 => [1,1,1,1], 2 => [2], 3 => [3,3,3] }
h.each{|k,v| h[k] = v.size}

You can achieve this by:
h.map { |a, b| [a, b.size] }.to_h
#=> {1=>4, 2=>1, 3=>3}

Here is one more way to achieve it:
h = { 1 => [1,1,1,1], 2 => [2], 3 => [3,3,3] }
p h.keys.zip(h.values.map(&:size)).to_h
#=> {1=>4, 2=>1, 3=>3}

There's an implementation of this method in the DeepEnumerable library: https://github.com/dgopstein/deep_enumerable/
It's called shallow_map_values:
>> require 'deep_enumerable'
>> h = { 1 => [9,2,3,4], 2 => [6], 3 => [5,7,1] }
>> h.shallow_map_values { |v| v.size }
=> {1=>4, 2=>1, 3=>3}

Related

transform keys and values with an array as one of them

I have the following Ruby hash
a = {
7 => [1469, 2283],
5 => [1469, 5464],
3 => [7561],
6 => [7952, 8114],
4 => []
}
and would like to get the keys that a number shows up in as a value
b = {
1469 => [7,5],
2283 => [7],
5464 => [5]
...
}
How would I do this? I'm sure there's some super slick way of getting it done.
Given:
a = {
7 => [1469, 2283],
5 => [1469, 5464],
3 => [7561],
6 => [7952, 8114],
4 => [1469, 2283],
2 => []
}
Use a default value of a new array in b:
b=Hash.new {|hsh, key| hsh[key] = [] }
a.each{|k,v| v.each{|n| b[n] << k} }
Or include the object creation with each_with_object:
b=a.each_with_object(Hash.new {|h,k| h[k] = []}) { |(k,v), h|
v.each{ |e| h[e] << k } }
Result b is:
{1469=>[7, 5, 4], 2283=>[7, 4], 5464=>[5], 7561=>[3], 7952=>[6], 8114=>[6]}
Using #each_with_object to iterate over the original hash and the values stored in each array and build up a new hash based on it.
a.each_with_object({}) do |(k, v), h|
v.each do |val|
h[val] ||= []
h[val] << k
end
end
Result:
{
1469 => [7, 5],
2283 => [7],
5464 => [5],
7561 => [3],
7952 => [6],
8114 => [6]
}
#dawg's answer is the way I would go
a.each_with_object(Hash.new {|h,k| h[k] = []}) do |(k,v),obj|
v.each{|e| obj[e] << k}
end
But here are a few other options: (a lot of allocations though)
Array#product and Hash#merge
a.each_with_object({}) do |(k,v),obj|
obj.merge!(v.product([[k]]).to_h) {|_,o,v| [*o,*v]}
end
#map then #reduce
a.map {|k,v| v.product([[k]]).to_h }
.reduce {|memo, h| memo.merge(h) {|_,o,n| o.concat(n)}}
This works too (don't ask questions)
a.map {|k,v| v.each_with_object(k)}
.reduce(&:+)
.group_by(&:shift)
.transform_values(&:flatten)

How to sum values inside array of hash with same keys

I want to sum the values of same keys like
arr = [{"69120090" => [1, 2, 3]}, {"69120090" => [4, 5, 6]}]
I need to result in:
result = [{"69120090" => [5, 7, 9]}]
Reduce by Hash#merge! with a block:
arr = [{"69120090"=> [1, 2, 3] }, {"69120090"=> [4, 5, 6] }]
arr.each_with_object({}) do |h, acc|
acc.merge!(h) { |_, v1, v2| v1.zip(v2).map(&:sum) }
end
#⇒ {"69120090"=>[5, 7, 9]}
The above accepts any number of hashes with any number of keys each.
Just to have another option, given the array:
arr = [{ a: [1, 2, 3], b:[8,9,0] }, { a: [4, 5, 6], c: [1,2,3] }, { b: [0,1,2], c: [1,2,3] } ]
You could write:
tmp = Hash.new{ |k,v| k[v] = [] }
arr.each { |h| h.each { |k,v| tmp[k] << v } }
tmp.transform_values { |k| k.transpose.map(&:sum) }
Which returns
tmp #=> {:a=>[5, 7, 9], :b=>[8, 10, 2], :c=>[2, 4, 6]}
As one liner:
(arr.each_with_object(Hash.new{ |k,v| k[v] = [] }) { |h, tmp| h.each { |k,v| tmp[k] << v } }).transform_values { |k| k.transpose.map(&:sum) }

hash.merge with block to add up sub-hash keys?

I have read something about hash merge with a block and this is working fine for simple, non-nested hashes in plain ruby. The following code results in {1=>2, 2=>4, 4=>6} as expected:
a = {1 => 1, 2 => 2, 4 => 3}
b = {1 => 1, 2 => 2, 4 => 3}
a.merge(b) { |key, value_a, value_b | value_a + value_b }
But the merge is not working for a nested hash structure, I get a NoMethodError (undefined method '+' for {1=>1, 2=>2}:Hash)
a = { "2018" => {1 => 1, 2 => 2, 4 => 3} }
b = { "2019" => {1 => 1, 2 => 2, 4 => 3} }
c = a.merge(b) { |key, value_a, value_b | value_a + value_b }
I have read about each_with_object and I am unsure how to use it. Is there a smart way to accomplish the merge of the values of the sub-hash? What do you think is the easiest way?
You can use Hash#deep_merge from active support to do this.
require 'active_support/all'
a = { k1: { k2: 1 } }
b = { k1: { k2: 2 } }
a.deep_merge(b) { |k, v1, v2| v1 + v2 }
# => { l1: { k2: 3 } }
Nested Hash, nested Hash#merge?
I changed the key of b to "2018"
a = { "2018" => {1 => 1, 2 => 2, 4 => 3} }
b = { "2018" => {1 => 1, 2 => 2, 4 => 3} }
c = a.merge(b) { |k, v1, v2| v1.merge(v2) { |kk, aa, bb | aa + bb } }
#=> {"2018"=>{1=>2, 2=>4, 4=>6}}
For your original values:
a = { "2018" => {1 => 1, 2 => 2, 4 => 3} }
b = { "2019" => {1 => 1, 2 => 2, 4 => 3} }
The result is
#=> {"2018"=>{1=>1, 2=>2, 4=>3}, "2019"=>{1=>1, 2=>2, 4=>3}}

ruby - group by repeating key of multiple hashes

I have the following array
t = [
{nil => 1, 10 => 2, 16 => 4, 5=> 10},
{nil => 9, 5 => 2, 17 => 3, 10 => 2},
{10 => 4, 5 => 9, 17 => 1}
]
how can I get this as result?
{nil => [1,9,0],10 => [2,2,4], 16 => [4,0,0], 5 => [10,2,9], 17=>[0,3,1]}
I've seen that I can use something like this
t.group_by{|h| h['key']}
but I'm not sure if I can put a regexp inside the brackets
Thanks in advance
Javier
EDIT:
Is just want to group by each key of each hash inside the array, if the key is not present then the value is 0 for that hash
How about this one for illegibility:
t = [
{nil => 1, 10 => 2, 16 => 4, 5=> 10},
{nil => 9, 5 => 2, 17 => 3, 10 => 2},
{10 => 4, 5 => 9, 17 => 1}
]
# Create hash of possible keys
keys = t.reduce({}) { |m, h| h.each_key { |k| m[k] = [] }; m }
# Iterate through array, for each hash, for each key, append the
# value if key is in hash or zero otherwise
t.reduce(keys) { |m, h| m.each_key { |k| m[k] << (h[k] || 0) }; m }
puts keys
#=> {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]}
Not the most elegant code I've ever written, but it does the job and is easy to understand:
def jqq(a)
keys = []
result = {}
a.each do |h|
keys += h.keys
end
keys.uniq.each do |key|
result[key] = []
a.each do |h|
h.default = 0
result[key] << h[key]
end
end
result
end
t = [
{nil => 1, 10 => 2, 16 => 4, 5=> 10},
{nil => 9, 5 => 2, 17 => 3, 10 => 2},
{10 => 4, 5 => 9, 17 => 1}
]
puts jqq(t)
# {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]}
I do not think there is any any function available
Just gave a try with hash
def do_my_work(data)
hash = {}
#get all keys first
arr.map{|m| m.keys}.flatten.uniq.each {|a| hash[a]=[]}
# Now iterate and fill the values
arr.each do |elm|
hash.each do |k,v|
hash[k] << (elm[k].nil? ? 0 : elm[k])
end
end
end
hash = do_my_work(t)
puts hash
# => {nil=>[1, 9, 0], 10=>[2, 2, 4], 16=>[4, 0, 0], 5=>[10, 2, 9], 17=>[0, 3, 1]}

Ruby merge hashes putting keys into csv string

Is there a clever way to achieve the following in Ruby?
hash1 = { "a" => 1, "b" => 2, "d" => 3}
hash2 = { "a" => 4, "b" => 5, "c" => 7}
hash3 = { "a" => 4, "d" => 7, "e" => 9}
puts hash1.csvMerge(hash2).csvMerge(hash3)
with the output being:
{ "a" => "1,4,4",
"b" => "2,5,0",
"c" => "0,7,0",
"d" => "3,0,7",
"e" => "0,0,9" }
What I'm trying to do is merge a bunch of Ruby hashes, in practice I have over a dozen, into a single hash where the values are combined into a comma separated string.
hash1.merge(hash2){|key, oldval, newval| [oldval,newval].join(",")}
=> {"a"=>"1,4", "b"=>"2,5", "d"=>3, "c"=>7}
hashes = [hash1, hash2, hash3]
keys = hashes.inject({}){|hh, h| hh = hh.merge(h); hh}.keys # the set of all keys #
default_hash = keys.inject({}){|d, k| d[k] = 0; d} # hash with value 0 for all keys #
complemented_hashes = hashes.map{|h| default_hash.merge(h)} # missing values filled in #
p Hash[complemented_hashes.map{|h| h.to_a}.flatten(1).group_by{|k, v| k}.
map{|k, v| [k, v.map{|k, v| v}.join(",")]}]
I dont know if this has performance issues
hashes = [hash1, hash2, hash3]
hash_with_all_keys = {}
hashes.each{|hash| hash_with_all_keys.merge!(hash)}
keys = hash_with_all_keys.keys
result_hash_mapping = keys.map do |key|
value = hashes.map{|hash| hash[key].to_i}.join(",")
[key, value]
end
result_hash = Hash[result_hash_mapping]
I could have replaced lines 2 to 4 with keys = hashes.inject({}){|merge_hash, hash| merge_hash.merge(hash)}.keys but I find it hard to read.
hash1 = { "a" => 1, "b" => 2, "d" => 3}
hash2 = { "a" => 4, "b" => 5, "c" => 7}
hash3 = { "a" => 4, "d" => 7, "e" => 9}
hashes = [hash1, hash2, hash3]
hashes.each{|h| h.each{|k,v| h[k] = v.to_s }}
res = hashes.inject{|m,h| m.merge(h){|k,old,new| "#{old},#{new}" }} #merge and glue
p res
#=> {"a"=>"1,4,4", "b"=>"2,5", "d"=>"3,7", "c"=>"7", "e"=>"9"}
Functional approach:
hashes = [hash1, hash2, hash3]
result = Hash[hashes.flat_map(&:keys).uniq.map do |key|
[key, hashes.map { |h| h[key] || 0 }.join(",")]
end]
#=> {"a"=>"1,4,4", "b"=>"2,5,0", "c"=>"0,7,0", "d"=>"3,0,7", "e"=>"0,0,9"}

Resources