Hello,
I've only been checking out Ruby for a couple of days, but today I came
across this problem.
If I do this:
#!/usr/bin/env ruby -w
string1 = "abc"
string2 = string1
string2.insert(-1, "def")
puts string1
puts string2
Then the result is:
abcdef
abcdef
How come string1 gets changed?!?
Thanks,
Marco
···
--
Posted via http://www.ruby-forum.com/.
irb(main):001:0> string1 = "abc"
=> "abc"
irb(main):002:0> string2 = string1
=> "abc"
irb(main):003:0> string2.object_id
=> 23129580
irb(main):004:0> string1.object_id
=> 23129580
Hope that helps.
···
On 1/26/07, Marco Guiseppe <kreatix@gmail.com> wrote:
Hello,
I've only been checking out Ruby for a couple of days, but today I came
across this problem.
If I do this:
#!/usr/bin/env ruby -w
string1 = "abc"
string2 = string1
string2.insert(-1, "def")
puts string1
puts string2
Then the result is:
abcdef
How come string1 gets changed?!?
Thanks,
Marco
--
Posted via http://www.ruby-forum.com/\.
check it out in irb.
Jason Mayer wrote:
check it out in irb.
Hope that helps.
Thanks for clearing that up, didn't know about object_id. Is this
behaviour common in programming languages? Seems weird to me.
Then again I'm very new to all of this.
This means I could do
string1 = "abc"
string2 = string1
string3 = string2
string4 = string3
and they all will change if I change string 4. What can I do to keep
string1 stay the same even if I change string 4?
···
--
Posted via http://www.ruby-forum.com/\.
It's not weird if you consider :
customer0 = Customer.new("John", "Doe")
customer1 = customer0
customer0.first_name = "Paul"
puts customer1.first_name
customer0 and customer1 points to the same instance.
Java strings are misleading.
Best regards,
···
On 1/27/07, Marco Guiseppe <kreatix@gmail.com> wrote:
Jason Mayer wrote:
>> check it out in irb.
>
> Hope that helps.
Thanks for clearing that up, didn't know about object_id. Is this
behaviour common in programming languages? Seems weird to me.
--
John Mettraux -///- http://jmettraux.openwfe.org
John Mettraux wrote:
customer0 = Customer.new("John", "Doe")
customer1 = customer0
customer0.first_name = "Paul"
puts customer1.first_name
customer0 and customer1 points to the same instance.
Yes, that makes sense. I've even found a much simpler solution to my
original problem that makes the question irrelevant.
Thanks, everyone!
···
--
Posted via http://www.ruby-forum.com/\.
Thanks very, very much, I was mired in a problem with this and you've
rescued me.
Bill Mosteller
Eloqua
Damian Terentyev wrote:
···
Hi!
I would like to notice, that if you ever need two separate objects, you
can always use a dup method, e.g:
string2 = string1.dup # Will have two different string instances
Your sincerely,
Damian/Three-eyed Fish
--
Posted via http://www.ruby-forum.com/\.