From: Robert Klemme Date: 2011-06-05T21:15:26+09:00 Subject: Re: CORE - Altering Behaviour of "each do" (default param "item") On 05.06.2011 07:53, Ilias Lazaridis wrote: > On 4 Ιούν, 21:02, Robert Klemme wrote: >> On 04.06.2011 16:19, Michael Sokol wrote: >> >>> Actually it would be possible, although very ugly. >> >>> You need to evaluate in the context of the current instance >>> (instance_eval) - not yield - the block you pass to the each method >>> of your object (an array in this case). >> >>> Then you can define a print method that behaves like a coroutine >>> (check out ruby fibers) and returns each element of your array. >> >> There is another approach which does not suffer from the side effect of >> changing self which can be disastrous: create a thread local which holds >> a stack of values and make item peek at the top element of it: >> >> class Object >> def new_each >> stack = (Thread.current[:__item__] ||= []) > > what does "(Thread.current[:__item__] ||= [])" do? You ask for things that modify the language and need meta programming in its implementation yet you do not seem to be comfortable with basic language functionality - or willing to find out. I sense a certain contradiction here. >> each do |x| >> stack.push x > [...] > >> This approach >> - does not change 'self' >> - is thread safe >> - is nesting safe > > This sounds good. > > But you suggestion adds Class#new_each. It doesn't. It adds Object#new_each. > The goal was, to alter the existent behaviour of Array#each. Ilias, this is not the goal assignment channel. You have your goals, other people have different goals. > I've tried to modify your code to achieve this, but I failed. Why don't you just post your code and let people comment on it? If you think about this failure you might find out why making Ruby more like Groovy in this respect might not be such a good idea altogether. If you read documentation of Enumerable you will see why it is a bad idea to attempt this with method #each. Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/