I have a hash:
input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"}
From it I want to get two hashes, one containing the pairs whose value (as integer) is positive, the other containing 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 enumerable object (like 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 the 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 use a version of Ruby prior 2.1 you can replace the Array#to_h
method (that was introduced in Ruby 2.1) like this:
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 must say that Enumerable#partition
is more appropriate, as @toro2k answered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With