如何定义一个可以通过 Struct 的实例方法共享访问的变量?
我可以像这样使用全局变量
$tmp
:
Triple = Struct.new :x, :y, :z do
def mul s
$tmp.x = x * s
$tmp.y = y * s
$tmp.z = z * s
return $tmp
end
end
$tmp = Triple[0.0, 0.0, 0.0]
one = Triple[1.0, 1.0, 1.0]
puts $tmp
puts one
one.mul 7.5
puts $tmp
puts one
:和:
$ /opt/src/ruby-3.3.5/bin/ruby --yjit -W0 example.rb
#<struct Triple x=0.0, y=0.0, z=0.0>
#<struct Triple x=1.0, y=1.0, z=1.0>
#<struct Triple x=7.5, y=7.5, z=7.5>
#<struct Triple x=1.0, y=1.0, z=1.0>
但我只希望变量可以在 Struct Triple 中访问,如下所示:
Triple = Struct.new :x, :y, :z do
@tmp = Triple[0.0, 0.0, 0.0]
def mul s
@tmp.x = x * s
@tmp.y = y * s
@tmp.z = z * s
return @tmp
end
end
:但是:
$ /opt/src/ruby-3.3.5/bin/ruby --yjit -W0 example.rb
example.rb:4:in `block in <main>': uninitialized constant Triple (NameError)
@tmp = Triple[0.0, 0.0, 0.0]
^^^^^^
虽然我很不清楚你在这里的意图,但你可以使用特征类(单例类)中的实例变量来实现你的目标
Triple = Struct.new :x, :y, :z do
class << self
def tmp
@tmp ||= new(0,0,0)
end
end
def tmp = self.class.tmp
def mul s
tmp.x = x * s
tmp.y = y * s
tmp.z = z * s
tmp
end
end
这将导致
one = Triple[1.0, 1.0, 1.0]
#=> #<struct Triple x=1.0, y=1.0, z=1.0>
one.tmp
#=> #<struct Triple x=1.0, y=1.0, z=1.0>
one.mul 7.5
#=> #<struct Triple x=7.5, y=7.5, z=7.5>
one
#=> #<struct Triple x=1.0, y=1.0, z=1.0>
one.tmp
#=> #<struct Triple x=7.5, y=7.5, z=7.5>