Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何根据条件将一个哈希拆分为两个哈希?_Ruby_Hash - Fatal编程技术网

Ruby 如何根据条件将一个哈希拆分为两个哈希?

Ruby 如何根据条件将一个哈希拆分为两个哈希?,ruby,hash,Ruby,Hash,我有一个杂烩: input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"} 从中我想得到两个散列,一个包含值(作为整数)为正值的对,另一个包含负值,例如: positive = {"a"=>"440", "d"=>"100" } negative = {"b"=>"-195", "c"=>"-163" } 如何使用最少的代码量实现这一点?您可以使用该方法根据条件拆分可枚举对象(如哈希

我有一个杂烩:

input = {"a"=>"440", "b"=>"-195", "c"=>"-163", "d"=>"100"} 
从中我想得到两个散列,一个包含值(作为整数)为正值的对,另一个包含负值,例如:

positive = {"a"=>"440", "d"=>"100" } 
negative = {"b"=>"-195", "c"=>"-163" }
如何使用最少的代码量实现这一点?

您可以使用该方法根据条件拆分可枚举对象(如哈希)。例如,要分离正值/负值,请执行以下操作:

input.partition { |_, v| v.to_i < 0 }
# => [[["b", "-195"], ["c", "-163"]], 
#     [["a", "440"], ["d", "100"]]]
如果您使用Ruby 2.1之前的版本,您可以将
数组#to_h
方法(在Ruby 2.1中引入)替换为如下:

evens, odds = input.partition { |_, v| v.to_i.even? }
               .map { |alist| Hash[alist] }
此实现使用:


我必须说,@toro2k回答说,
Enumerable#partition
更合适

positive = Hash.new
negative = Hash.new

input.each_pair  { |var,val|
  if val.to_i > 0 
    positive[var] = val
  else
    negative[var] = val
  end
}

不清楚是要分隔偶数/奇数值还是正值/负值。我要正值和负值。
分区
更好。。。m'hai Fregatooo:D
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"}
positive = Hash.new
negative = Hash.new

input.each_pair  { |var,val|
  if val.to_i > 0 
    positive[var] = val
  else
    negative[var] = val
  end
}