Ruby. kluge... , eval , :
>> a = 5
=> 5
>> b = :a
=> :a
>> eval "#{b} = 4"
=> 4
>> eval "#{a}"
=> 4
>> eval "#{b}"
=> 4
, b :a, , eval:
>> b
=> :a
>> b + 1
NoMethodError: undefined method `+' for :a:Symbol
... , , . , binding ...
' ' Ruby?
@ Paul.s has an answer, if you can change the declaration point as a wrapper object, but if you can control the reference point, then here is the class BasicReferenceI tried:
class BasicReference
def initialize(r,b)
@r = r
@b = b
@val = eval "#{@r}", @b
end
def val=(rhs)
@val = eval "#{@r} = #{rhs}", @b
end
def val
@val
end
end
a = 5
puts "Before basic reference"
puts " the value of a is #{a}"
b = BasicReference.new(:a, binding)
b.val = 4
puts "After b.val = 4"
puts " the value of a is #{a}"
puts " the value of b.val is #{b.val}"
It is output:
Before basic reference
the value of a is 5
After b.val = 4
the value of a is 4
the value of b.val is 4
source
share