Ruby 1.9.2 - 多个 splat 参数问题

发布于 2024-10-21 17:12:29 字数 977 浏览 15 评论 0原文

Ruby 新手,正在解决一个问题,我试图在方法中接受多个 splat 参数。我想我明白为什么它会给我编译错误,但我不知道如何修复它。任何有关如何在参数中使用多个 splat 的帮助都会有所帮助。在此先感谢您的任何指导。

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)

New to Ruby and working on a problem where I'm trying to accept multiple splat arguments in the method. I think I understand why it's giving me the compile error, but I'm not sure how to fix it. Any help with how to use multiple splats in the arguments would be helpful. Thank you in advance for any guidance here.

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尘曦 2024-10-28 17:12:29

使用 splat 参数的示例:

def sum(*nums)
  sum = 0 
  nums.each do |num|
    sum += num 
  end 
  sum 
end

puts sum(1,2,3)

请注意如何直接指定参数,而不是在 [] 内指定。

如果该方法定义了第二个 splat 参数,则无法确定第一个参数何时结束、第二个参数何时开始。

Example of using splat arguments:

def sum(*nums)
  sum = 0 
  nums.each do |num|
    sum += num 
  end 
  sum 
end

puts sum(1,2,3)

Notice how the arguments are specified directly, not inside [].

If the method defined a second splat argument, one couldn't determine when the first one ends and the second begins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文