【问题标题】:Does Ruby have right operators similar to Python?Ruby 是否有类似于 Python 的正确运算符?
【发布时间】:2016-03-29 07:16:39
【问题描述】:

Pythondefines左右运算符使用__radd____rsub__等方法

Ruby 有类似的东西吗?

class N32
  def +( other )
    2
  end
end
a = N32.new
a + 3 # return 2
3 + a # return error N32 can't be coerced into Fixnum

【问题讨论】:

  • 呃……我不这么认为。

标签: ruby class oop


【解决方案1】:

该类需要一个 coerce 方法才能工作:

class N32

  def +( other )
    2
  end 

  def coerce(other)
    [self, other]
  end

end

a = N32.new
a + 3 # return 2
3 + a # return 2

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2014-06-20
    • 2011-04-12
    • 2018-02-15
    • 2011-10-14
    • 2017-06-03
    • 1970-01-01
    • 2012-01-28
    • 2013-05-24
    相关资源
    最近更新 更多