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

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

问题描述:

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

这个作品在红宝石1.8.6,但是当我尝试做这在1.8.5,并尝试发送多个ARG我得到的线沿线的一个错误:

错误的参数数目(2 X)

其中X为参数的个数该特定的方法需要。我宁愿不重写所有的通知方法 - Ruby 1.8.5可以处理这个吗?

+2

出于好奇,为什么*不*使用Ruby 1.8.6? – Matchu 2010-11-29 03:51:38

一个很好的解决方案是使用散列改用命名参数:

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' 
)