References not behaving the same with string vs My_object
-
Hi
I realised my own_objects and basic objects like strings are not referenced the same way!
class MyObject attr_accessor ;value def initialize(value) @value = value end end obj1=MyObject.new('hip') obj2=obj1 obj2.value='hop' puts obj1.value # ==> return 'hop' puts obj1.object_id,obj2.object_id # ==> they have the same id! (pointer?) a='hip' b=a b='hop' puts a # ==> return 'hip' puts a.object_id,b.object_id # ==> they have a different id! (reference?)
How can i know the type of object I use will automaticaly clone when a copy is modified ?
Can I force ruby to act the same with all objects (clone any copied object using = without the need to use the .clone method)?Thanks
ako
-
You need to get straight on some basic aspects of Ruby.
A named variable in Ruby holds a reference to a Ruby Object. When you assign a value to a variable, you are attaching the reference to a particular Object. So, for example
obj2=obj1
causes both of these variables to refer to the same underlying instance of MyObject. When you then invoke its value= method
obj2.value='hop'
You are modifying the contents of the original instance of MyObject. Both variables still refer to this same, single instance.
However, in your second example, you are not modifying the Object referenced by a and b. When you write
b='hop'
you are creating a new String object to hold 'hop' and causing b to reference it. Since a still refers to the original String containing 'hip', what you report is the result.
-
b='hop'
is the same as:
b=String::new('hop')
The Ruby interpreter "reads" the literal string
'hop'
and passes it toString::new
"behind the curtain".=
is the reference assignment operator.a="hip"
means "the variablea
shall reference the string object'hip'
."a=b
means "the variablea
shall reference the object thatb
is referencing."
Advertisement