我需要一个散列来涉及其他散列,并根据用户选择的内容执行操作。代码:
puts "Indicate name of the bank:"
bank_name = gets.chomp
puts "Money to invest:"
money_invested = gets.to_i
puts "Indicate time of investment:"
time_investment = gets.to_i
bank_one = { 30 => 1.0219, 45 => 1.0336, 60 => 1.0467 }
bank_two = { 30 => 1.0348, 45 => 1.5897, 60 => 1.0987 }
back_three = { 30 => 1.0489, 45 => 1.5999, 60 => 1.1589 }
investment_calculation = money_invested * NEWHASHNEEDEDHERE[time_investment]
puts "Your money is now of $#{investment_calculation}."
根据用户在bank_name
上的选择,正确的散列应该被寻址,从而操作。我需要一个包含这段代码的“ super 哈希”:
bank_one = { 30 => 1.0219, 45 => 1.0336, 60 => 1.0467 }
bank_two = { 30 => 1.0348, 45 => 1.5897, 60 => 1.0987 }
back_three = { 30 => 1.0489, 45 => 1.5999, 60 => 1.1589 }
而且,这个新的散列应该在这个变量中被寻址:
investment_calculation = money_invested * NEWHASHNEEDEDHERE[time_investment]
最佳答案
您可以如下所示定义散列的散列,并使用[]
运算符访问它
interest_rates = {
"bank_one" => { 30 => 1.0219, 45 => 1.0336, 60 => 1.0467 },
"bank_two" => { 30 => 1.0348, 45 => 1.5897, 60 => 1.0987 },
"bank_three" => { 30 => 1.0489, 45 => 1.5999, 60 => 1.1589 }
}
investment_calculation = money_invested * interest_rates[bank_name][time_investment]
关于ruby - 哈希需要根据用户的输入进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33943654/