需要根据用户的输入来解决哈希问题

时间:2015-11-26 16:50:20

标签: ruby hash

我需要哈希来涉及其他哈希,并根据用户选择的内容执行操作。代码:

    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上选择的内容,应该添加正确的哈希,从而进行操作。我需要一个“超级哈希”,包括这段代码:

    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]

1 个答案:

答案 0 :(得分:4)

您可以定义哈希哈希,如下所示,并使用[]运算符

访问它
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]