我有一个哈希,其中包含模型中城市的出现次数,我希望将nil
或blank
个键和值合并为一个并重命名新的单个键
例如
@raw_data = {nil => 2, "" => 2, "Berlin" => 1, "Paris" => 1}
# to
@corrected_data = {"undefined" => 4, "Berlin" => 1, "Paris" => 1}
我已经从Rubydoc查看了合并方法,但只有两个键相似才合并,但在这种情况下nil
和""
不一样。
我还可以创建一个新哈希并添加if nil or blank
语句并将值添加到新的undefined
键,但这似乎很乏味。
答案 0 :(得分:1)
我做:
@raw_data = {nil => 2, "" => 2, "Berlin" => 1, "Paris" => 1}
key_to_merge = [nil, ""]
@correct_data = @raw_data.each_with_object(Hash.new(0)) do |(k,v), out_hash|
next out_hash['undefined'] += v if key_to_merge.include? k
out_hash[k] = v
end
@correct_data # => {"undefined"=>4, "Berlin"=>1, "Paris"=>1}
答案 1 :(得分:1)
Ruby无法自动确定您要对由两个"类似的"表示的值做什么?键。您必须自己定义映射。一种方法是:
def undefined?(key)
# write your definition of undefined here
key.nil? || key.length == 0
end
def merge_value(existing_value, new_value)
return new_value if existing_value.nil?
# your example seemed to add values
existing_value + new_value
end
def corrected_key(key)
return "undefined" if undefined?(key)
key
end
@raw_data = {nil => 2, "" => 2, "Berlin" => 1, "Paris" => 1}
@raw_data.reduce({}) do |acc, h|
k, v = h
acc[corrected_key(k)] = merge_value(acc[corrected_key(k)], v)
acc
end
# {"undefined" => 4, "Berlin" => 1, "Paris" => 1}