Ruby的新手,我正在尝试接受方法中的多个splat参数。我想我理解为什么它给我编译错误,但我不知道如何解决它。任何有关如何在参数中使用多个splats的帮助都会有所帮助。提前感谢您的任何指导。
def find_max_expenses(salary, save_prcnt, *pre_ret_g_rates, *post_ret_g_rates, epsilon)
years = pre_ret_g_rates.count
savings = nest_egg_variable(salary, save_prcnt, pre_ret_g_rates)
savings = savings[-1]
low = 0
high = savings
expenses = (low + high) / 2
# can use the [-1] at the end is equivalent to the code below
remaining_money = post_retirement(savings, post_ret_g_rates, expenses) #[-1]
remaining_money = remaining_money[-1]
while remaining_money > epsilon # the value we want to stay above
if remaining_money > 0
low = expenses
else
high = expenses
end
expenses = (high + low) / 2
remaining_money = post_retirement(savings, post_ret_g_rates, expenses)
p remaining_money = remaining_money[-1]
end
p expenses
end
find_max_expenses(10000, 10, [3, 4, 5, 0, 3], [10, 5, 0, 5, 1], 0.01)
答案 0 :(得分:7)
使用splat参数的示例:
def sum(*nums)
sum = 0
nums.each do |num|
sum += num
end
sum
end
puts sum(1,2,3)
注意如何直接指定参数,而不是[]
内部。
如果方法定义了第二个splat参数,则无法确定第一个参数何时结束,第二个参数何时开始。