From: Justin Collins Date: 2010-03-27T05:34:52+09:00 Subject: Re: Creating a gsub! method for Arrays Derek Cannon wrote: > Derek Cannon wrote: > >> class Array >> def gsub!(pattern, replacement) >> each { |x| >> x.gsub!(pattern, replacement) >> } >> end >> end >> > > Just out of curiosity, does anyone know how Ruby knows what "each" is > referring to in this case? It works as intended -- I'm just curious as > to HOW. > If I understand your question correctly, "each" is being called on self, which will be an instance of Array. "each" is already defined for Array, and "gsub!" is just being added to the class. In the example below, you expect meth2 to be able to call meth1. It is analogous to the above. class A def meth1 puts "hi" end def meth2 meth1 end end A.new.meth2 -Justin