Given a String instance, how to create a different but equivalent one

Given a String instance, how to create a different but equivalent one

The code below shows the incorrect way and two correct ways
to create a second string instance that equal to a given string
instance.

Q1: Are there better ways to do this than the two I concocted?
Q2: How can I create a proc to invoke it with each of my candidate
assignment statements

I am interest in this issue because I made the naive assignment in a
project I am working on and
had to waste time trying debugging it.

Thanks in advance,
Richard

Version 1: Wrong!

os = “abc” # Original String
ws = os # Thinking ws can be modified independently of os.
3.times { ws << (ws[-1] + 1).chr; puts ws }
while ws.size > os.size
ws.chop; puts ws
end

Version 2: OK

puts
os = “abc” # Original String
ws = String.new(os) # ws is a reference to a different string
oobject than os but initially equal to os
3.times { ws << (ws[-1] + 1).chr; puts ws }
while ws.size > os.size
ws.chop!; puts ws
end

Version 3: OK

puts
os = “abc” # Original String
ws = os + “” # A less verbose way to get a new string object
initially equal to os
3.times { ws << (ws[-1] + 1).chr; puts ws }
while ws.size > os.size
ws.chop!; puts ws
end

RichardOnRails wrote:

I am interest in this issue because I made the naive assignment in a
ws = os # Thinking ws can be modified independently of os.
oobject than os but initially equal to os
initially equal to os
3.times { ws << (ws[-1] + 1).chr; puts ws }
while ws.size > os.size
ws.chop!; puts ws
end

Use String.dup to create a copy

irb(main):050:0> s1=‘hello’
=> “hello”
irb(main):050:0> s2=s1
=> “hello”
irb(main):049:0> s1.eql? s2
=> true
irb(main):048:0> s1.equal? s2
=> true

irb(main):047:0> s3=s1.dup
=> “hello”
irb(main):046:0> s3
=> “hello”
irb(main):045:0> s3.eql? s1
=> true
irb(main):044:0> s3.equal? s1
=> false


Kind Regards,
Rajinder Y.

http://DevMentor.org

Do Good! - Share Freely, Enrich and Empower people to Transform their
lives.

On Oct 26, 1:13 am, Rajinder Y. [email protected] wrote:

ws = os # Thinking ws can be modified independently of os.
oobject than os but initially equal to os
initially equal to os
=> “hello”
=> true
irb(main):044:0> s3.equal? s1
=> false


Kind Regards,
Rajinder Y.

http://DevMentor.org

Do Good! - Share Freely, Enrich and Empower people to Transform their lives.

Hi Rajinder ,

Use String.dup to create a copy

Thanks. I “knew” there was a “right way” in Ruby.

Best wishes,
Richard

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs