2010/2/19 Glenn Ritz <glenn_ritz / yahoo.com>: > Robert Klemme wrote: >> On 02/18/2010 10:39 PM, Glenn Ritz wrote: >>>> >>>> %w(cat dog mouse).each { |e| s =3D 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? =A0I mean, you can *always* have a reference = to >> the instance around. >> >> s =3D %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? =A0Passing the collection into the >> block during iteration feels wrong. =A0For example, typically when >> iterating modifications of the underlying collection are dangerous. =A0W= hy >> 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. =A0So I was thinking that it would be good if I could refer to th= e > array itself within the block. =A0I 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] =3D> 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] =3D> 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. =A0So 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 --=20 remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/