2

How do I multiply the non-negative number values of a hash by a number (for example: 2) and for the negative values just return 0?

For example, with this hash (with variable years keys):

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

The result would be: (-2.0 gives 0.0, 3.0*2=6.0, 1.0*2=2.0)

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

I tried this, but I can not figure out how to get 0 instead of the negative value:

hash.map { |k, v| [k, v.to_f * 2] }.to_h
=> {"year2020"=>-4.0, "year2021"=>6.0, "year2022"=>2.0}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Chris
  • 55
  • 4

3 Answers3

3

You can use Hash#transform_values (introduced in 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} 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
2

How about

hash.each do |key, value|
  v = value.to_f
  hash[key] = v <= 0 ? 0.0 : 2.0 * v
end
pjs
  • 18,696
  • 4
  • 27
  • 56
0

you can try this

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