0

This question claims that you have use hacks like eval to change a Hash that was passed as a parameter. I expect this result:

def change_hash(hash)
  hash[:non_existing_key] = :value
end

opts = {}
change_hash(opts)
opts # => {:non_existing_key => :value}

not to be possible since the Hash should be copied to the method by value. What is going on here?

Community
  • 1
  • 1
milch
  • 986
  • 8
  • 13
  • The question you link is really not relevant, because they are using eval to dynamically specify the variable name and the hash key name. This instead is a duplicate of your question: http://stackoverflow.com/questions/1872110/is-ruby-pass-by-reference-or-by-value – Marco Sandrini Feb 11 '16 at 09:20
  • *pass by reference* and *call by value* don't really apply to Ruby. Wikipedia uses a 3rd term: [call by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) – Stefan Feb 11 '16 at 09:23
  • @MarcoSandrini The accepted answer on that question is very vague and even the comments on that answer seem to contradict themselves, and some of the other (even highly up voted) answers are even mutually exclusive. – milch Feb 11 '16 at 10:05
  • Ok, to answer your question about what goes on in your code: when you call `change_hash(opts)` the *reference* to the hash object is passed "by value" . Which means that if you change the value of the parameter (e.g. `hash = 10`), the original object will not be modified, but if you use the parameter to access the original object (e.g. `hash[:non_existing_key] = :value`), the changes will occur on the original object. – Marco Sandrini Feb 11 '16 at 10:33

0 Answers0