"-2.0", "year2021" => "-6ren">
gpt4 book ai didi

ruby - 将哈希值乘以一个数字,负值返回 0

转载 作者:行者123 更新时间:2023-12-02 19:41:00 25 4
gpt4 key购买 nike

如何将哈希的非负数值乘以一个数字(例如:2),并且对于值仅返回 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#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}

关于ruby - 将哈希值乘以一个数字,负值返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60142171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com