From: Glenn Parker Date: 2005-02-10T02:05:45+09:00 Subject: Re: Method arguments Nash Kabbara wrote: > Hmmm. Is it safe to pass a Hash and modify it in a function then use it? > > for example: > > a = Hash.new > modify(a) > do_something_useful(a) > > after reading the response below, it's making me think how hashs behave > and whether it's safe to do the above. Sure, it's safe, and it (probably) does exactly what you would expect. Ignore the following if you don't want to entertain my rambling mind. What if Hash was immutable (like Fixnum)? class Hash private :[]= def assign(key, val) copy = self.clone copy[key] = val return copy end end x = { "a" => 1 } y = x x = x.assign("a", 3) # y["a"] is still 1 Not terribly useful or efficient. :) Note: I think it would be more useful if Ruby's built-in assignment operator evaluated to the LHS instead of the RHS. What if we want to go the other way and make Fixnum mutable (like Hash)? Ruby won't override basic assignment (=), so use =~ instead. class MutableFixnum def initialize(v) @value = v.to_i end def =~(v) @value = v.to_i end def +(a) @value + a.to_i end def inspect @value.to_s end end class Fixnum def to_mutable return MutableFixnum.new(self) end end x = 1.to_mutable y = x x =~ x + 1 p y => 2 What fun! But maybe not what you would have expected. Apparently, we prefer it when variables refering to the same Hash all change when one of those variables is operated on. Yet, it feels strange when variables refering to the same "number" all change when one of those variables is operated on. -- Glenn Parker | glenn.parker-AT-comcast.net |