简体   繁体   English

如何在Ruby 1.8.5中重新传递多个方法参数?

[英]How do I re-pass multiple method arguments in Ruby 1.8.5?

I'm using ruby 1.8.5 and I'd like to use a helper method to help filter a user's preferences like this: 我正在使用ruby 1.8.5,我想使用一个辅助方法来帮助过滤用户的首选项,如下所示:

def send_email(user, notification_method_name, *args)
  # determine if the user wants this email
  return if !user.send("wants_#{notification_method_name}?")

  # different email methods have different argument lengths
  Notification.send("deliver_#{notification_method_name}", user, *args)
end

This works in ruby 1.8.6, however when I try to do this in 1.8.5 and try to send more than one arg I get an error along the lines of: 这在ruby 1.8.6中有效,但是当我尝试在1.8.5中执行此操作并尝试发送多个arg时,出现以下错误:

wrong number of arguments (2 for X) 参数数量错误(对于X,为2)

where X is the number of arguments that particular method requires. 其中X是特定方法所需的参数数量。 I'd rather not rewrite all my Notification methods - can Ruby 1.8.5 handle this? 我不想重写我所有的Notification方法-Ruby 1.8.5可以处理吗?

A nice solution is to switch to named-arguments using hashes: 一个很好的解决方案是使用哈希切换到命名参数:

def  send_email(args)
  user = args[:user]
  notification_method_name = args[:notify_name]

  # determine if the user wants this email
  return if !user.send("wants_#{notification_method_name}?")

  # different email methods have different argument lengths
  Notification.send("deliver_#{notification_method_name}", args)
end

send_email(
  :user        => 'da user',
  :notify_name => 'some_notification_method',
  :another_arg => 'foo'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM