我有一个哈希:
input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"}
Run Code Online (Sandbox Code Playgroud)
从中我想得到两个哈希,一个包含其值(作为整数)为正,另一个包含负值的对,例如:
positive = {"a"=>"440", "d"=>"100" }
negative = {"b"=>"-195", "c"=>"-163" }
Run Code Online (Sandbox Code Playgroud)
如何使用最少量的代码实现此目的?
tor*_*o2k 14
您可以使用该Enumerable#partition
方法根据条件拆分可枚举对象(如散列).例如,要分隔正/负值:
input.partition { |_, v| v.to_i < 0 }
# => [[["b", "-195"], ["c", "-163"]],
# [["a", "440"], ["d", "100"]]]
Run Code Online (Sandbox Code Playgroud)
然后,要获得所需的结果,您可以使用map
和to_h
将键/值数组转换为哈希:
negative, positive = input.partition { |_, v| v.to_i < 0 }.map(&:to_h)
positive
# => {"a"=>"440", "d"=>"100"}
negative
# => {"b"=>"-195", "c"=>"-163"}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Ruby 2.1之前的版本,则可以替换此Array#to_h
方法(在Ruby 2.1中引入),如下所示:
evens, odds = input.partition { |_, v| v.to_i.even? }
.map { |alist| Hash[alist] }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2785 次 |
最近记录: |