如何根据值更新ruby哈希?

时间:2014-04-23 11:28:11

标签: ruby-on-rails ruby hash

我有以下输入

a = {"Mar-14"=>"440", "Jan-14"=>"-1958190", "Feb-14"=>"-1634613", "Apr"=>"100"}

我想要这样的输出

positive = {"Mar-14"=>"440","Apr"=>"100"}
negative = {"Jan-14"=>"-1958190", "Feb-14"=>"-1634613"}

如何完成这项工作?

注意:输出格式需要哈希

1 个答案:

答案 0 :(得分:4)

Hash#select可行:

negative = a.select { |k, v| v.to_i < 0 }
#=> {"Jan-14"=>"-1958190", "Feb-14"=>"-1634613"}

positive = a.select { |k, v| v.to_i >= 0 }
#=> {"Mar-14"=>"440", "Apr"=>"100"}

还有Enumerable#partition,但它会返回一个数组,因此您必须重新映射它:

negative, positive = a.partition { |k, v| v.to_i < 0 }.map(&:to_h)