From: 7stud -- Date: 2012-12-29T11:09:01+09:00 Subject: Re: Ruby Koans regarding Hashes. > Derrick B. wrote in post #1090528: > I had that mostly correct in my head, but two references to the same > array??? After creating the new Hash object, the hash variable is just > the Hash reference, but the indexed Hash reference ( like hash[:one] ) > points to the array reference, right? > >>> hash = Hash.new { |hash, key| hash[key] = [] } > => {} >>> hash > => {} >>> hash[:one] > => [] >>> hash.object_id > => 269913890 >>> hash[:one].object_id > => 269881860 > > Two different id's. Or did I do that wrong? Two references to the same > array in that assignment expression above doesn't sound right. Your > other example: 1) The block does not create the hash. If you look at the block: Hash.new { |hash, key| hash[key] = [] } ...you can see that the block takes a hash as an argument. The hash gets created elsewhere. 2) You cannot look at a block and know what a method returns. A block is like an argument to a method. In essence, you are passing a function to the method. Here is an example: def do_stuff(x, y, &block) #&block is the syntax to capture the block #in a variable if block_given? block_return_val = block.call puts "Block returns: %s" % block_return_val end 'hello' #This is the return val of do_stuff end do_stuff_return_val = do_stuff(10, 20) {'goodbye'} puts "do_stuff returns: %s" % do_stuff_return_val --output:-- Block returns: goodbye do_stuff returns: hello However, it is pretty obvious if you are a programmer that a method named new is going to return a new object. So when you write: hash = Hash.new { |hash, key| hash[key] = [] } ... hash is going to be a reference to a new Hash. Therefore, you can deduce that the new() method of the Hash class returns a reference to a new Hash. Note that the block returns whatever a method named []= in the Hash class returns. -- Posted via http://www.ruby-forum.com/.