The Pug
The Pug

Reputation: 25

There's some way to reuse string?

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?

Upvotes: 1

Views: 128

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54253

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" 

Upvotes: 2

spickermann
spickermann

Reputation: 106952

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"

Upvotes: 4

Related Questions