How to work with hash in ruby? -
my hash example:
{"79_6"=>"0", "85_6"=>"1", "86_6"=>"1", "79_8638"=>"0", "80_8638"=>"0", "81_8638"=>"0", "82_8638"=>"1", "83_8638"=>"1", "84_8638"=>"0", "85_8638"=>"1", "86_8638"=>"0", "79_8639"=>"0", "80_8639"=>"0", "81_8639"=>"0", "82_8639"=>"0", "83_8639"=>"0", "84_8639"=>"0", "85_8639"=>"0", "86_8639"=>"0", "80_8640"=>"0", "81_8640"=>"1", "82_8640"=>"1", "83_8640"=>"1", "84_8640"=>"0", "85_8640"=>"0", "86_8640"=>"0"}
i need parameters key 1
:
["85_6", "86_6", "82_8638", "83_8638", "85_8638", "81_8640", "82_8640", "83_8640"]
next, need group:
{"6"=>"85, 86", "8638"=> "83, 82, 85", "8640" => "81, 82, 83"}
hash.select { |_, v| v == '1' } .keys .map { |e| e.split('_') } .group_by(&:pop) .map { |k, v| [k, v.join(', ')] } .to_h #⇒ { # "6" => "85, 86", # "8638" => "82, 83, 85", # "8640" => "81, 82, 83" # }
Comments
Post a Comment