Is it possible to modify an existing ruby string without creating a new
one ?
If for example I have the following code :
x = “first string”
x = “second string”
between asigning values , the object_id() is different . Is there a
possibility to modify the first string so that after the modifications
the object_id will be the same ?
I would like to know how I could get to an empty string from “first
string”. I would like to know if a clear method exists,or something
alike. I’m using ruby 1.8.7 .
On Sat, Jan 31, 2009 at 7:40 PM, Tsunami S.er [email protected]
wrote:
Is it possible to modify an existing ruby string without creating a new
one ?
yes
If for example I have the following code :
x = “first string”
x “second string”
x.clear << “second string”
x.sub! /first/, “second”
x[0…4] = “second”
I would like to know how I could get to an empty string from “first
string”.
I guess my first example answers this.
HTH
Robert
irb(main):005:0> x = “string”
=> “string”
irb(main):006:0> x.clear
NoMethodError: undefined method `clear’ for “string”:String
from (irb):6
from :0
Perhaps you’re using a different version of ruby .
On Sat, Jan 31, 2009 at 7:40 PM, Tsunami S.er [email protected]
wrote:
the object_id will be the same ?
a = “first string”
=> “first string”
a.replace “second string”
=> “second string”
a
=> “second string”
a.object_id
=> 340702860
a.replace “third string”
=> “third string”
a.object_id
=> 340702860
I would like to know how I could get to an empty string from “first
string”. I would like to know if a clear method exists,or something
alike. I’m using ruby 1.8.7 .
a.replace “”
Jesus.
On Sat, Jan 31, 2009 at 7:57 PM, Tsunami S.er [email protected]
wrote:
irb(main):005:0> x = “string”
=> “string”
irb(main):006:0> x.clear
NoMethodError: undefined method `clear’ for “string”:String
from (irb):6
from :0
Perhaps you’re using a different version of ruby .
Yup, I thought this was back-ported to 1.8.7 my error.
R
x.delete!(x) << “new value”
Before and after, the object id will be identical.
Sent from my iPhone
Is it possible to modify an existing ruby string without creating a new
one ?
[…]
between asigning values , the object_id() is different
I could be totally wrong but IMHO you’re asking for two different
things.
As soon as you have something like “second string” in your code you
will create a second string. You can assign this to the variable (the
variable’s value will have a different object_id) or replace its
content with that string (the variables value will have same object_id
as before but in between you created a second string).
3.times do
puts “---------”
x = “one”.tap {|s| puts “one #{s.object_id}”}
p x, x.object_id
x.replace(“two”.tap {|s| puts “two #{s.object_id}”})
p x, x.object_id
end