ruby variable as same object (pointers?)

前端 未结 7 986
-上瘾入骨i
-上瘾入骨i 2021-01-01 03:22
>> a = 5
=> 5
>> b = a
=> 5
>> b = 4
=> 4
>> a
=> 5

how can I set \'b\' to actually be \'a\' so that in the exa

7条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 03:34

    I'm no Ruby expert. But for a technically crazy kluge...that would only work if you felt like going through eval every time you worked with a variable:

    >> a = 5
    => 5
    >> b = :a
    => :a
    >> eval "#{b} = 4"
    => 4
    >> eval "#{a}"
    => 4
    >> eval "#{b}"
    => 4
    

    Note that a direct usage of b will still give you :a and you can't use it in expressions that aren't in eval:

    >> b
    => :a
    >> b + 1
    NoMethodError: undefined method `+' for :a:Symbol
    

    ...and there are certainly a ton of caveats. Such as that you'd have to capture the binding and pass it around in more complex scenarios...

    'pass parameter by reference' in Ruby?

    @Paul.s has an answer for if you can change the point of declaration to be a wrapper object, but if you can only control the point of reference then here's a BasicReference class I 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}"
    

    This outputs:

    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
    

提交回复
热议问题