进一步详细说明@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#*