【发布时间】:2015-11-24 18:18:25
【问题描述】:
我尝试在这里寻找一些类似的案例,但没有成功。
我希望用户首先介绍一笔金额,然后他需要说明天数:“30”、“45”或“60”,而不是其他选项,最后是程序将乘以每个固定数字的金额。这个数字取决于用户选择的天数。如果他选择30,“金额*1.0219”; 45:“金额*1.0336”; 60:“金额 * 1.0467”。
到目前为止,这是我写的代码:
puts "Indicate money to invest"
money_invested = gets.to_i
puts "Indicate time of investment"
time_investment = gets.to_i
investment_calculation = { 30 => 1.0219, 45 => 1.0336, 60 => 1.0467 }
# will be `nil` if not one of the defined ones
我知道哈希中已经发生了一些可怕的事情,所以我决定就此打住。我不确定=> 是否意味着我想要的意思,即:乘。
【问题讨论】:
-
您可以使用哈希 (
mult = investment_calculation[time]) 来获得乘数,但您也可以使用if语句 (mult = if time==30 then 1.0219; elsif time==45 then 1.0336; else 1.0467; end) 或case语句 (mult = case time; when 30 then 1.0219; when 45 then 1.0336; else 1.0467; end。