将哈希值乘以一个数字,return 0 为负值

Multiply the values of a hash by a number, and return 0 for the negative values

如何将散列的 非负数 数值乘以一个数字(例如:2)以及 负数 值只是 return 0?

例如,使用此散列(具有可变年份键):

hash = {"year2020" => "-2.0", "year2021" => "3.0", "year2022" => "1.0",...}

结果将是:(-2.0 给出 0.0, 3.0*2=6.0, 1.0*2=2.0)

result = {"year2020" => "0.0", "year2021" => "6.0", "year2022" => "2.0",...}

我试过了,但我不知道如何得到 0 而不是负值:

hash.map { |k, v| [k, v.to_f * 2] }.to_h
=> {"year2020"=>-4.0, "year2021"=>6.0, "year2022"=>2.0}

怎么样

hash.each do |key, value|
  v = value.to_f
  hash[key] = v <= 0 ? 0.0 : 2.0 * v
end

您可以使用Hash#transform_values(在Ruby v2.4中引入):

hash = {"year2020"=>"-2.0", "year2021"=>"3.0", "year2022"=>"1.0" }

hash.transform_values { |v| [2*v.to_f, 0].max }
  #=> {"year2020"=>0, "year2021"=>6.0, "year2022"=>2.0} 

你可以试试这个

hash.each do |key,value|
    if value.to_f>=0.0
        hash[key]=(value.to_f*2.0).to_s
    else
        hash[key]="0.0"
    end   
end