From: Robert Klemme Date: 2011-07-28T21:29:36+09:00 Subject: Re: How do we read this line of code? On Wed, Jul 27, 2011 at 10:54 PM, Stu wrote: > Hello abder.rahman.ali > > each is an important part of ruby and it is something people from > other programming languages tend to find a bit confusing at first. It > is basically a foreach loop( i.e. a loop that defeats the possibility > of a off-by-one index based bug/error.) It is also a common design > pattern. > > It should be read as: > > traverse each item in collection Careful: we have no other context information and we do not know what @x actually points to. So we can only say something like Invoke the block for each item which method @x.each yields. > The final note about each. It is redesigned( overloaded) in many > classes to work with a specific task of collections to aid the > programmers with a common interface. If you ever create a class which > acts as a collection it is common to redefine each to work within that > class as well as other rubyisms such as to_s and so on. The more > common the paradigm/syntax; the more fluid your mental and > programmatic flow will work within the creation of your own programs. > It also allows easy adoption( and adaption) for others to use your > libraries. But then again, it's not hard to create a class which follows the Enumerable contract either: class Silly include Enumerable def each rand(47).times { yield rand(11) } self end end Now with @x = Silly.new we can do @x.each do |x| puts x end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/