【问题标题】:Why does ruby method with = at the end not allow more then one argument为什么最后带有=的ruby方法不允许超过一个参数
【发布时间】:2014-06-10 04:16:18
【问题描述】:

这是在一个共享库中,我必须使它向后兼容。

原始方法

   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

【问题讨论】:

  • 对于那些反对并要求关闭的人来说,这提出了一个关于 ruby​​ 语言以及如何实现功能的好问题。在将人们赶出网站之前请考虑一下。
  • setter 方法(例如以= 结尾的方法)应保留用于通过赋值= 设置实例变量。在您的情况下,最好将其转换为真正的方法调用,因为您的方法内部不会发生赋值。原始设计的核心存在缺陷,使用= 能否请您发布价格设置方法,以便我们了解分配是如何发生的。

标签: ruby


【解决方案1】:

如果您希望它向后兼容,请利用数组的力量:

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

【讨论】:

  • @archie - 将我的答案更新为向后兼容
  • +1 出色的答案更新,即使它违反了 setter 方法的标准约定。
  • 这会起作用并且看起来很干净,而不是 if is_a?解决方案,这也有效。谢谢。
  • 没有必要在你原来的答案上使用删除线,只是为了有别的东西。如果我们愿意,我们可以通过查看编辑历史来查看您的更改。只需删除旧的内容并输入您想要阅读的答案即可;结果将减少视觉上的噪音。
  • @theTinMan - 你说得对,我删除了旧答案
【解决方案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"}

它也将保持向后兼容性。

【讨论】:

  • 您还可以添加一个num.is_a? Array 分支以允许o.rrp_exc_sales_tax = [ 2, "USD" ]
  • @muistooshort:是的,数组也同样可以达到目的,我觉得通过哈希知道哪个变量代表什么。
【解决方案3】:

因为它看起来像是一个简单的赋值操作。如果该操作需要参数化,那么让它看起来像一个方法调用更有意义。此外,具有多参数赋值语句会使语言语法复杂化。

【讨论】:

  • 有没有ruby文档的参考,可以给团队解释一下。
  • 这实际上不是assignment,而是一个setter方法。 assignment 应该/将发生在 setter 方法中。它们语法相似,但功能不同。
猜你喜欢
  • 2011-09-15
  • 2023-03-11
  • 2021-07-20
  • 1970-01-01
  • 2022-01-19
  • 2016-11-16
  • 2015-07-12
  • 1970-01-01
  • 2014-11-20
相关资源
最近更新 更多