← Back to Upcase

Hash arguments to functions in ruby -- explain?


(Philip Bradley) #1

Can someone explain why a hash passed into a method is altered whereas a simpler type is not?

 require 'pry'


def change_it(a)
  a = 5
end

def change_it2(a)
  a['a'] = 5
end

foo = 2
change_it(foo)
puts foo  # prints "2", foo is unchanged

hoo = {}
change_it2(hoo)
puts hoo  # the hash hoo has been altered

(Philip Bradley) #2

I figured it out. This post helped a lot:

http://stackoverflow.com/questions/22827566/ruby-parameters-by-reference-or-by-value/22827949#22827949