繁体   English   中英

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

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

我正在使用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

这在ruby 1.8.6中有效,但是当我尝试在1.8.5中执行此操作并尝试发送多个arg时,出现以下错误:

参数数量错误(对于X,为2)

其中X是特定方法所需的参数数量。 我不想重写我所有的Notification方法-Ruby 1.8.5可以处理吗?

一个很好的解决方案是使用哈希切换到命名参数:

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