How to split a hash in two hashes based on a condition?
I have a hash:
input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"} From it I want to get two hashes, one of which contains pairs whose value (as a whole) is positive, and the other contains negative values, for example:
positive = {"a"=>"440", "d"=>"100" } negative = {"b"=>"-195", "c"=>"-163" } How can I achieve this using the minimum amount of code?
You can use the Enumerable#partition method to split an enumerated object (such as a hash) based on a condition. For example, to separate positive / negative values:
input.partition { |_, v| v.to_i < 0 } # => [[["b", "-195"], ["c", "-163"]], # [["a", "440"], ["d", "100"]]] Then, to get the desired result, you can use map and to_h to convert key / value arrays to hashes:
negative, positive = input.partition { |_, v| v.to_i < 0 }.map(&:to_h) positive # => {"a"=>"440", "d"=>"100"} negative # => {"b"=>"-195", "c"=>"-163"} If you are using a version of Ruby prior to version 2.1, you can replace the Array#to_h (which was introduced in Ruby 2.1) as follows:
evens, odds = input.partition { |_, v| v.to_i.even? } .map { |alist| Hash[alist] } This implementation uses Enumerable#group_by :
input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"} grouped = input.group_by { |_, v| v.to_i >= 0 }.map { |k, v| [k, v.to_h] }.to_h positives, negatives = grouped.values positives #=> {"a"=>"440", "d"=>"100"} negatives #=> {"b"=>"-195", "c"=>"-163"} I have to say that Enumerable#partition more suitable as @ toro2k replied.