On 8/8/07, Jano Svitok <jan.svitok@gmail.com> wrote:
On 8/8/07, FireAphis <FireAphis@gmail.com> wrote:
> Hello,
>
> I need to iterate through a list and handle two elements on every
> iteration. That is I'd like to do something like
>
> [1,2,3,4,5].each { |x, y| puts x.to_s + y.to_s }
>
> 12
> 23
> 34
> 45
>
> This code doesn't work off course.
> I can iterate using indices
>
> 0.upto(list.size-1) { |i| puts list[i] + list[i+1] }
>
> But it looks ugly to me. Do you know any elegant tricks that don't use
> list indices?
>
> Thanks
> FireAphis
I can't quite follow how that will get to the result. Can you walk me
through it? My first reaction is that it's awfully full of "magic
dots", but I'm willing to be enlightened.... (And I honestly
can't puzzle it out.)
map without a parameter creates a Proxy object that contains the
enumeration and the method name :map.
It's method_missing forwards everything to the enumeration via send
and the method name, thus
map.join becomes
map{|x| x.send(:join)}
it is not everybody's cup of tea, but I love it, obviously.
Labrador, the LAZY programmers best friend
class EmptyProxy < EmptyObject
def initialize object, message @enum = object @message = message
end
end
class Dispatcher < EmptyProxy
def method_missing mth, *args, &blk @enum.send(@message){|x| x.send(mth.to_sym,*args)}
end # def method_missing mth, *args, &blk
end # class Dispatcher < EmptyProxy
Cheers
Robert
···
On 8/8/07, dblack@rubypal.com <dblack@rubypal.com> wrote:
map without a parameter creates a Proxy object that contains the
enumeration and the method name :map.
It's method_missing forwards everything to the enumeration via send
and the method name, thus
map.join becomes
map{|x| x.send(:join)}
it is not everybody's cup of tea, but I love it, obviously.
Labrador, the LAZY programmers best friend
class EmptyProxy < EmptyObject
def initialize object, message @enum = object @message = message
end
end
class Dispatcher < EmptyProxy
def method_missing mth, *args, &blk @enum.send(@message){|x| x.send(mth.to_sym,*args)}
end # def method_missing mth, *args, &blk
end # class Dispatcher < EmptyProxy
Cheers
Robert
--
[...] as simple as possible, but no simpler.
-- Attributed to Albert Einstein