2014-04-24 29 views
4

这是在一个共享库中,我必须使它向后兼容。为什么ruby方法在末尾不允许超过一个参数

原始方法

def rrp_exc_sales_tax=(num) 
     price_set(1, num, currency_code) 
    end 

需要加强,并添加CURRENCY_CODE

def rrp_exc_sales_tax=(num, currency_code=nil) 
     print "num=#{num}" 
     print "currency_code=#{currency_code}" 
     price_set(1, num, currency_code) 
    end 


some_class.rrp_exc_sales_tax=2, "USD" 

num=[2, "USD"] 
currency_code= 

没有价值被分配到CURRENCY_CODE

+1

为了谁是downvoting,并要求关闭的乡亲,这引起了人们对Ruby语言和功能如何一个很好的问题被执行。请在将人员排除在网站之前进行考虑。 – archie

+0

setter方法(例如以'='结尾的方法)应该保留用于通过赋值'='来设置实例变量。在你的情况下,将它转换为真正的方法调用会更好,因为赋值不会在你的方法内部发生。原始设计的核心问题是使用'=',您可以发布价格设置方法,以便我们看到如何分配。 – engineersmnky

回答

5

如果你希望它是向后兼容的,杠杆率在阵列的权力:

def rrp_exc_sales_tax=(arr) 
    num, currency_code = arr 
    price_set(1, num, currency_code) 
end 

some_class.rrp_exc_sales_tax=2, "USD" 
# => num=2 
# => currency_code="USD" 

some_class.rrp_exc_sales_tax=2 
# => num=2 
# => currency_code=nil 
+0

@archie - 更新我的答案是向后兼容的 –

+0

+1优秀的答案**更新**即使它违背了setter方法的标准约定。 – engineersmnky

+0

这将工作,看起来很干净,而不是如果is_a?解决方案,这也是可行的。谢谢。 – archie

3

因为它的意思是看起来像一个简单的赋值操作。如果需要对该操作进行参数化,则使其看起来像调用方法更有意义。而且,具有多参数赋值语句会使语言语法复杂化。

+0

有没有参考ruby文档,所以我可以向团队解释。 – archie

+0

这实际上并不是“赋值”,而是一种设置方法。 “赋值”应该/将在setter方法内发生。它们在语法上相似,但在功能上不相同。 – engineersmnky

2

你应该尝试一下这样的: -

def rrp_exc_sales_tax(num, currency_code=nil) 
    print "num=#{num}" 
    print "currency_code=#{currency_code}" 
    price_set(1, num, currency_code) 
end 

为了保持向后兼容性,你可以这样做:现在

def rrp_exc_sales_tax=(num) 
    if num.is_a?(Hash) 
    print "num=#{num["num"]}" 
    print "currency_code=#{num["currency_code"]}" 
    price_set(1, num["num"], num["currency_code"]) 
    else 
    print "num=#{num}" 
    print "currency_code=#{currency_code}" 
    price_set(1, num, currency_code) 
    end 
end 

,在新的实现,你会这样称呼它: -

rrp_exc_sales_tax={"num"=>2, "currency_code" => "USD"} 

它也会保持向下兼容性。

+0

当然,我不可能是共享库。 – archie

+1

你也可以添加一个'num.is_a? Array'分支以允许'o.rrp_exc_sales_tax = [2,“USD”]'。 –

+0

@ muistooshort:是的数组也将同样的目的,我觉得哈希一个知道哪个变量代表什么。 – Saurabh

相关问题