Ruby: how can I copy a variable without pointing to the same object?

前端 未结 3 1210
温柔的废话
温柔的废话 2020-12-03 00:23

In Ruby, how can I copy a variable such that changes to the original don\'t affect the copy?

For example:

phrase1 = \"Hello Jim\"
phrase2 = phrase1
p         


        
相关标签:
3条回答
  • 2020-12-03 00:46

    Using your example, instead of:

    phrase2 = phrase1
    

    Try:

    phrase2 = phrase1.dup
    
    0 讨论(0)
  • 2020-12-03 00:50
    phrase1 = "Hello Jim"
       # => "Hello Jim"
    
    phrase2 = Marshal.load(Marshal.dump(phrase1))
       # => "Hello Jim"
    
    phrase1.gsub!("Hello","Hi")
       #  => "Hi Jim" 
    
    puts phrase2
       # "Hello Jim"
    
    puts phrase1
       # "Hi Jim"
    
    0 讨论(0)
  • 2020-12-03 01:13

    As for copying you can do:

    phrase2 = phrase1.dup
    

    or

    # Clone: copies singleton methods as well
    phrase2 = phrase1.clone
    

    You can do this as well to avoid copying at all:

    phrase2 = phrase1.gsub("Hello","Hi")
    
    0 讨论(0)
提交回复
热议问题