0

我正在使用 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 是特定方法所需的参数数量。我宁愿不重写我所有的通知方法——Ruby 1.8.5 可以处理这个吗?

4

1 回答 1

0

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

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'
)
于 2010-11-29T04:02:02.740 回答