我正在尝试弄清楚coerce方法。当我定义*方法和coerce方法时。integer * Point触发coerce,但"" * Point不触发。为什么?
错误是:
coerce.rb:34:in `*': no implicit conversion of Point into Integer (TypeError)   from coerce.rb:34:in `<main>'代码是:
class Point
  def initialize x,y
    @x,@y = x,y
  end
  def * x
    p "* called" 
    @x *= x
    @y *= x
  end
  def coerce other
    p 'coerce called'
    if other.is_a? String
      p "converted"
      [self, other.to_i]
    else
      [self,other]
    end
    #[3,other]
  end
end
p1= Point.new 1,1
p1*2
p p1
2*p1
p p1
p p1.coerce(2)
p "string test====="
"2" * p1输出:
"* called"
#<Point:0x00564f5de89dd0 @x=2, @y=2>
"coerce called"
"* called"
#<Point:0x00564f5de89dd0 @x=4, @y=4>
"coerce called"
[#<Point:0x00564f5de89dd0 @x=4, @y=4>, 2]
"string test====="
coerce.rb:34:in `*': no implicit conversion of Point into Integer (TypeError)
    from coerce.rb:34:in `<main>'谁能告诉我为什么和如何让"2" * p1工作?
发布于 2019-05-14 00:08:12
这里的问题是,虽然Ruby允许您为此重新定义运算符,但这些运算符在排序方面非常特殊。
记住这段代码:
point * 2最终被Ruby理解为:
point.send(:*, 2)它是您定义的处理这种特殊情况的方法,Point#*。
而这段代码:
2 * point最终被理解为:
2.send(:*, point)它会转移到Integer#*,而你无法控制它。虽然你可以修补它,但这似乎是一个非常糟糕的想法。最好的方法是记录你的系统是如何工作的,并展示正确排序的例子。
在Ruby中,二元运算符中的左手边值基本上是发号施令的,右手边的值只是一个乘客。
https://stackoverflow.com/questions/56107203
复制相似问题