我正在嘗試為我的多分量變數創建一個快速設定方法(在我的真實代碼中它是 Vector2d)。
我想使用該=方法的覆寫版本。
例如:
def my_vector=(x, y)
@my_vector = Vector2d.new(x, y)
end
但它不起作用,因為當我嘗試呼叫此方法時,我收到一個錯誤:
my_vector=1, 2 # => wrong number of arguments (given 1, expected 2)
my_vector=(1, 2) # => syntax error, unexpected ',', expecting ')'
my_vector=[1, 2] # => wrong number of arguments (given 1, expected 2)
這是我的測驗套件:
# With one param it works
def my_var=(value)
@var = value
end
self.my_var=1
puts "var: " @var.to_s
# With 2 params it doesn't work
def my_other_var=(value1, value2)
@other_var_component_1 = value1
@other_var_component_2 = value2
end
# Nothing works:
# self.my_other_var=1, 2
# self.my_other_var=(1, 2)
# self.my_other_var=[1, 2]
puts "other_var_component_1: " @other_var_component_1.to_s
puts "other_var_component_2: " @other_var_component_2.to_s
uj5u.com熱心網友回復:
正如@eugen 正確所說,您不能將兩個引數傳遞給像
self.my_vector = 1, 2
您可以實作的最接近的事情是使用模式匹配解包引數:
def myvector=(arg)
arg => [x, y]
@my_vector = Vector2d.new(x, y)
end
foo.my_vector = [1, 2]
另一種方法是定義一個簡單的輔助方法v,以便您可以撰寫
foo.my_vector = v 1, 2
uj5u.com熱心網友回復:
您正在定義一個名為my_vector=(或my_other_var=在您的第二個示例中)的方法。
如果你只是想用
my_vector = 1, 2
ruby 會將其解釋為對my_vector變數的賦值。
您必須使用send才能呼叫您定義的方法,如
self.send :my_vector=, 1, 2
這有點丑陋,但我沒有看到其他解決方法。
uj5u.com熱心網友回復:
對提供的代碼稍作修改以使用陣列引數:
def my_other_var=(values)
@other_var_component_1 = values[0]
@other_var_component_2 = values[1]
end
self.my_other_var=[1, 2]
"other_var_component_1: " @other_var_component_1.to_s
#=> other_var_component_1: 1
"other_var_component_2: " @other_var_component_2.to_s
#=> other_var_component_2: 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426753.html
下一篇:用N個字符替換行首的N個空格
