From: Glenn Ritz Date: 2010-02-19T23:07:28+09:00 Subject: Re: Adding self to Enumerable Robert Klemme wrote: > On 02/18/2010 10:39 PM, Glenn Ritz wrote: >>> >>> %w(cat dog mouse).each { |e| s = self; puts "self: #{s.inspect}, e: >>> #{e}" } >>> >>> or better: >>> >>> %w(cat dog mouse).each { |e| puts "self: #{self.inspect}, e: #{e}" } >> >> >> I want to be able to refer to the array receiver inside of the block. > > What is the point of that? I mean, you can *always* have a reference to > the instance around. > > s = %w(cat dog mouse) > s.each {|e| ...} > > Or, in 1.9 > > %w(cat dog mouse).tap {|s| s.each {|e| ...}} > > Even if you pass around a block for later usage with #each you can make > sure the collection is accessible inside the block. > > What is the real use case of this? Passing the collection into the > block during iteration feels wrong. For example, typically when > iterating modifications of the underlying collection are dangerous. Why > do you need this feature? > > Kind regards > > robert Sometimes in statistics it's good to be able to access the previous element in a collection, not just the current one like in Ruby's each method. So I was thinking that it would be good if I could refer to the array itself within the block. I realize now that there are probably better ways to do this. :-) Also, I find the with_index method on Enumerable objects interesting and was trying to figure out a way to write a similar method. So I asked the question just to learn more on what I think is an interesting feature of the language. Thanks, Glenn -- Posted via http://www.ruby-forum.com/.