From: Robert Klemme Date: 2012-02-23T18:20:41+09:00 Subject: Re: cheered to soon enumerable woos On Thu, Feb 23, 2012 at 9:58 AM, Catsquotl wrote: > What i think is happening is this. > > each is called with a block. > this block iterates over each element of the flattened array. The block does nothing by itself. The block is an anonymous callback function. > But then? > what does the last call to each(&block) on line 2 do? > > when called with a block > say self.each{|n| puts n} > nothing seems to happen and the flattened array is returned. Actually "self" should be returned conventionally. But that is just a detail which has nothing to do with iteration. I can't really believe that nothing happens. Let's just try this in IRB: irb(main):001:0> class X irb(main):002:1> attr_accessor :a, :b, :c irb(main):003:1> def each(&block) irb(main):004:2> [a,b,c].flatten.each(&block) irb(main):005:2> end irb(main):006:1> end => nil irb(main):007:0> x = X.new => # irb(main):008:0> x.a = 1 => 1 irb(main):009:0> x.b = 2 => 2 irb(main):010:0> x.c = 3 => 3 irb(main):011:0> x.each {|n| puts n} 1 2 3 => [1, 2, 3] Now please show your code which does not do anything. > Can anyone say what's going on? > I've read up on blocks, procs and lambda's for the last few hours, but I > can't seem to get to grips with the logic. The block is simply forwarded to the second call of #each. Before that #flatten just ensures that nested Arrays are expanded and every element of them is visited individually. >> def each(&block) >>   [@afk, @name, @chname, @locatie, @aard, @actie].flatten.each(&block) >> end Btw. that method should conventionally return "self" at the end. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/