1

In case,

A = "A"
B = "#{A}"

It's B = "A", right?

And now I would like to change (A = "C") and want B to change by effect of A too.

Is there some way to do that?

Azeem
  • 11,148
  • 4
  • 27
  • 40
The Pug
  • 25
  • 5
  • 1
    Check this out: https://stackoverflow.com/questions/7169277/ruby-variable-as-same-object-pointers – iGian Jul 15 '19 at 05:38
  • the string is already interpreted and will not change after that. what is the exact use case? – Pascal Jul 15 '19 at 06:10

2 Answers2

4

Let's talk about naming conventions first. Uppercase identifiers are used for constants in Ruby. Per default assigning a new value to an already initialized constant raises a warning in Ruby:

A = 'B'
A = 'C'
#=> warning: already initialized constant A
#=> warning: previous definition of A was here

Therefore I will use normal instance variables and reader methods in the following example. As Pascal Betz already pointed out: If you want b to depend on the current value of a then b should be a method:

def b
  @a
end

@a = 'A'
b
#=> "A"

@a = 'C'
b
#=> "C"
spickermann
  • 100,941
  • 9
  • 101
  • 131
2

If you do this:

a = "A"
b = "#{a}"

a and b are strings with the same content, but they're not the same objects:

b == a
# => true
b.equal? a
# => false
a.object_id
# => 24494240
b.object_id
# => 24679880

Ruby strings are mutable. So if b and a refer to the same string, modifying a will automatically update b too:

a = "A"
# => "A" 
b = a
# => "A" 
a.replace 'C'
# => "C" 
b
# => "C" 

It works in both directions:

b.gsub!('C', 'D')
# => "D" 
a
# => "D" 
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124