From: Robert Klemme Date: 2010-02-19T23:16:25+09:00 Subject: Re: Adding self to Enumerable 2010/2/19 Glenn Ritz : > 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? > > 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. :-) Enumerable#each_cons comes to mind... Also, Enumerable#inject works pretty well: irb(main):003:0> (1..5).inject {|a,b| p [a,b];b} [1, 2] [2, 3] [3, 4] [4, 5] => 5 irb(main):004:0> (1..5).inject(nil) {|a,b| p [a,b];b} [nil, 1] [1, 2] [2, 3] [3, 4] [4, 5] => 5 irb(main):005:0> > 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. I hope you found out. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/