From: Mischa Fierer Date: 2008-08-28T18:54:23+09:00 Subject: Confused by scope in ruby Hello, I've been writing in ruby for a bit, but ran into something while working on a project that struck me as weird, and could not find a ready explanation. Sorry if this is something super basic... Here is a simplified example. My question is: Why is the hash not empty at the end? class Hmmm def why_not_empty? hash = {} puts "Start: hash = #{hash.to_s}" [1, 2, 3, 4, 5].each do |num| put_in_hash(num, hash) end puts "End hash:\n#{hash.to_s}" # i would expect this to be {} end def put_in_hash(num, hsh) hsh[num.to_s] = "hello from hash index #{num}.\n" return nil end def number num = 2 puts "Start number: #{num}" change_number?(num) puts "End number: #{num}" end def change_number?(num) num = 3 end end @a = Hmmm.new @a.why_not_empty? @a.number Output: Start: hash = End hash: 1hello from hash index 1. 2hello from hash index 2. 3hello from hash index 3. 4hello from hash index 4. 5hello from hash index 5. Start number: 2 End number: 2 The number, as I would expect, stays at two, but the hash is actually changed by the method, as if I were passing it a pointer in C or something... -- Posted via http://www.ruby-forum.com/.