2

假设我有这个简单的类:

class Color
  attr_accessor :rgb
  def initialize(ary)
    @rgb = ary
  end
  def +(other)
    other = Color.new(other) unless Color === other
    Color.new(@rgb.zip(other.rgb).map {|p| [p.reduce(:+), 255].min })
  end
end

我知道这是一种不好的实现方式,但这是我能想到的最短方式。

c100 = Color.new([100, 100, 100])
c100 + c100         #=> Color(200, 200, 200)
c100 + c100 + c100  #=> Color(255, 255, 255)

如果我将数组作为颜色,它也可以工作:

c100 + [50, 50, 50] #=> Color(150, 150, 150)

但我不能这样做:

[50, 50, 50] + c100 #=> TypeError: can't convert Color into Array

定义coerce不起作用。我怎样才能让它工作?

4

2 回答 2

3

这是因为代码

[50, 50, 50] + c100

调用+Array 上的方法,而不是 Color,并且该方法无法将颜色转换为 Array。

相比之下,

 c100 + [50, 50, 50]

确实调用了 Color 的+方法。

但是,即使您在 Color 中定义了转换方法:

class Color
def to_ary
return @rgb
end
end

Array 方法不会像您期望的那样工作;结果将是两个数组的连接,因为 Array 的+方法连接它们的操作数,而不是添加它们的元素:

irb>[50,50,50]+c100
=> [50,50,50,100,100,100]

在这里,结果将是一个数组,而不是一个颜色。

编辑:

我看到使这项工作的唯一方法是使用+Array 的方法来处理接收 Color 作为第二个操作数的特殊情况。但是,我承认这种方法相当丑陋。

class Array
  alias color_plus +
  def +(b)
    if b.is_a?(Color)
      return b+self
    end
    return color_plus(b)
  end
end
于 2011-09-25T23:02:59.143 回答
1

进一步详细说明@peter-o 的答案,我想出了这个实现,虽然从某种意义上说它重新定义了 Array 的几种方法很丑,但它几乎可以成为预期行为的一个很好的解决方法,我不认为我会曾经在生产代码中适应过这个,但我真的很喜欢这个挑战......很抱歉在颜色主题上存在分歧,但我不知道减号和时间的预期行为会是什么。

class Array
  alias :former_plus :+
  alias :former_minus :-
  alias :former_times :*

  def +(other)
    former_plus(other)
  rescue TypeError
    apply_through_coercion(other, :+)
  end

  def -(other)
    former_minus(other)
  rescue TypeError
    apply_through_coercion(other, :-)
  end

  def *(other)
    former_times(other)
  rescue TypeError
    apply_through_coercion(other, :*)
  end

  # https://github.com/ruby/ruby/blob/ruby_1_9_3/lib/matrix.rb#L1385
  def apply_through_coercion(obj, oper)
    coercion = obj.coerce(self)
    raise TypeError unless coercion.is_a?(Array) && coercion.length == 2
    coercion[0].public_send(oper, coercion[1])
  rescue
    raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}"
  end
  private :apply_through_coercion
end

挑战之一是确保对Point#-方法的反向调用不会返回意外结果,因此@coerced实例变量作为对象上的控制标志。

class Point
  attr_reader :x, :y

  def initialize(x, y)
    @x, @y, @coerced = x, y, false
  end

  def coerce(other)
    @coerced = true
    [self, other]
  end

  def coerced?; @coerced end

  def +(other)
    other = Point.new(*other) if other.respond_to? :to_ary
    Point.new(@x + other.x, @y + other.y)
  end

  def -(other)
    other = Point.new(*other) if other.respond_to? :to_ary
    if coerced?
      @coerced = false; other + (-self)
    else self + (-other) end
  end

  def -@; Point.new(-@x, -@y) end

  def *(other)
    case other
    when Fixnum then Point.new(@x*other, @y*other)
    when Point  then Point.new(@x*other.x, @y*other.y)
    when Array  then self * Point.new(*other)
    end
  end
end

毕竟,这段代码设法实现的是将强制功能添加到它不存在的 Array 类中,显式地添加到methodsArray#+和.Array#-Array#*

于 2012-07-07T19:00:27.983 回答