R
RichardOnRails
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
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