ruby variable as same object (pointers?)

前端 未结 7 1050
-上瘾入骨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:42

    As has been noted the syntax you are using can not be done. Just throwing this out there though you could make a wrapper class it depends what you actually want to do

    ruby-1.8.7-p334 :007 > class Wrapper
    ruby-1.8.7-p334 :008?>   attr_accessor :number
    ruby-1.8.7-p334 :009?>   def initialize(number)
    ruby-1.8.7-p334 :010?>     @number = number
    ruby-1.8.7-p334 :011?>   end
    ruby-1.8.7-p334 :012?> end
     => nil 
    ruby-1.8.7-p334 :013 > a = Wrapper.new(4)
     => # 
    ruby-1.8.7-p334 :014 > b = a
     => # 
    ruby-1.8.7-p334 :015 > a.number = 6
     => 6 
    ruby-1.8.7-p334 :016 > a
     => # 
    ruby-1.8.7-p334 :017 > b
     => # 
    

提交回复
热议问题