Ruby 自定义 class 对象的运算符重载无法正常工作
Ruby operator-overloading not working properly for a custom class object
我的 +/- 覆盖方法需要一些帮助,它不影响 wektor 数组的元素。
class Wektor
attr_accessor :coords
def initialize(length)
@coords = Array.new(length, 0)
end
def set!(w)
@coords = w.dup
self
end
%i(* /).each do |op|
define_method(op) do |n|
coords.map! { |i| i.send(op, n) }
self
end
end
%i(- +).each do |op|
define_method(op) do |v|
@coords.zip(v).map { |a, b| a.send(op, b) }
self
end
end
def shift_right!
coords.rotate!
coords[0] = 0
self
end
end
所以基本上如果 a = Wektor.new(4).set!([1,2,3,4]
和 b = Wektor.new(4).set!([1,1,1,1]
我想 a-b
设置 a = [0,1,2,3]
这种方法有什么问题?它没有改变任何东西 - a
仍然设置为 [1,2,3,4]
。
我尝试使用 IRB 进行调试,但它没有给我任何关于问题所在的线索。
代码对我来说看起来不错,但我是编写 ruby-way 代码的初学者(我不是这段代码的作者),我很难发现错误。
*
和 /
工作正常,向量应该是 multiplied/divided 的标量。
试试这个:
%i(- +).each do |op|
define_method(op) do |v|
@coords = @coords.zip(v.coords).map { |a, b| a.send(op, b) }
self
end
end
您想要 zip
数组,因此在 v
上调用 coords
可以实现。此外,map
执行给定的块和 returns 收集的结果,您正在丢弃它们。
你知道 Ruby 有一个 Vector class 吗?
2.1.5 :001 > require 'matrix'
=> true
2.1.5 :002 > a = Vector[1,2,3,4]
=> Vector[1, 2, 3, 4]
2.1.5 :003 > b = Vector[1,1,1,1]
=> Vector[1, 1, 1, 1]
2.1.5 :004 > a - b
=> Vector[0, 1, 2, 3]
2.1.5 :005 > a * 3
=> Vector[3, 6, 9, 12]
我的 +/- 覆盖方法需要一些帮助,它不影响 wektor 数组的元素。
class Wektor
attr_accessor :coords
def initialize(length)
@coords = Array.new(length, 0)
end
def set!(w)
@coords = w.dup
self
end
%i(* /).each do |op|
define_method(op) do |n|
coords.map! { |i| i.send(op, n) }
self
end
end
%i(- +).each do |op|
define_method(op) do |v|
@coords.zip(v).map { |a, b| a.send(op, b) }
self
end
end
def shift_right!
coords.rotate!
coords[0] = 0
self
end
end
所以基本上如果 a = Wektor.new(4).set!([1,2,3,4]
和 b = Wektor.new(4).set!([1,1,1,1]
我想 a-b
设置 a = [0,1,2,3]
这种方法有什么问题?它没有改变任何东西 - a
仍然设置为 [1,2,3,4]
。
我尝试使用 IRB 进行调试,但它没有给我任何关于问题所在的线索。
代码对我来说看起来不错,但我是编写 ruby-way 代码的初学者(我不是这段代码的作者),我很难发现错误。
*
和 /
工作正常,向量应该是 multiplied/divided 的标量。
试试这个:
%i(- +).each do |op|
define_method(op) do |v|
@coords = @coords.zip(v.coords).map { |a, b| a.send(op, b) }
self
end
end
您想要 zip
数组,因此在 v
上调用 coords
可以实现。此外,map
执行给定的块和 returns 收集的结果,您正在丢弃它们。
你知道 Ruby 有一个 Vector class 吗?
2.1.5 :001 > require 'matrix'
=> true
2.1.5 :002 > a = Vector[1,2,3,4]
=> Vector[1, 2, 3, 4]
2.1.5 :003 > b = Vector[1,1,1,1]
=> Vector[1, 1, 1, 1]
2.1.5 :004 > a - b
=> Vector[0, 1, 2, 3]
2.1.5 :005 > a * 3
=> Vector[3, 6, 9, 12]