Dup a Constant

I have a constant in my helper :
MYCONSTANT = { :opt => { :title => “abcdef” } }

In my view :
<%
joke = PeopleHelpers::MYCONSTANT.dup
joke[:opt][:title] = nil
#if i debug there, PeopleHelpers::MYCONSTANT = {:opt => {:title =>
nil}}
%>

I can’t understand this behaviour and how fix it ?
Is it a bug ?

In fact the previous example doesn’t change the value of
PeopleHelpers::MYCONSTANT

but if I do :
<%
joke = PeopleHelpers::MYCONSTANT.dup
joke[:opt][:title].sub!(‘a’,‘b’)
#if i debug there, PeopleHelpers::MYCONSTANT = {:opt => {:title =>
bbcdef}}
%>

the value changed… why ?

On 25 March 2010 14:47, Adrien C. [email protected] wrote:

the value changed… why ?

My understanding is that dup makes a copy of the hash contents, but
since the contents are themselves references rather than simple
objects you end up with a new hash containing references to the same
objects, which can then be modified as you have noted (even though
they are notionally constant).

Colin

On Mar 25, 2010, at 10:34 AM, Adrien C. wrote:

I can’t understand this behaviour and how fix it ?
Is it a bug ?

No, #dup and #clone typically make shallow copies.

irb> orig = { :opt => { :title => ‘hello’ } }
=> {:opt=>{:title=>“hello”}}
irb> dup = orig.dup
=> {:opt=>{:title=>“hello”}}
irb> dup[:opt][:title]
=> “hello”
irb> dup[:opt][:title] = nil
=> nil
irb> dup
=> {:opt=>{:title=>nil}}
irb> orig
=> {:opt=>{:title=>nil}}

irb> orig = { :opt => { :title => ‘hello’ } }
=> {:opt=>{:title=>“hello”}}
irb> clone = orig.clone
=> {:opt=>{:title=>“hello”}}
irb> clone[:opt][:title]
=> “hello”
irb> clone[:opt][:title] = nil
=> nil
irb> clone
=> {:opt=>{:title=>nil}}
irb> orig
=> {:opt=>{:title=>nil}}

If you want a “deep” copy, usually you Marshal and un-Marshal:

irb> orig = { :opt => { :title => ‘hello’ } }
=> {:opt=>{:title=>“hello”}}
irb> marshaled = Marshal.load(Marshal.dump(orig))
=> {:opt=>{:title=>“hello”}}
irb> marshaled[:opt][:title]
=> “hello”
irb> marshaled[:opt][:title] = nil
=> nil
irb> marshaled
=> {:opt=>{:title=>nil}}
irb> orig
=> {:opt=>{:title=>“hello”}}

-Rob

Rob B. http://agileconsultingllc.com
[email protected]

Thank you very much for your explanations :slight_smile:

adrien

2010/3/25 Colin L. [email protected]

%>
Colin


COQUIO Adrien
[email protected]

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