Chris Shea
3/25/2007 7:41:00 AM
On Mar 25, 2:20 am, unbewusst.s...@wortanschahung.com.invalid (Une
Bévue) wrote:
> f it doesn't exist allready, i'd like to add another each method to
> String similar to each_byte except it loops over chars for example :
>
> "zero".each_char{|c| puts c}
>
> would print-out :
> z
> e
> r
> o
>
> i know how to add a new method to a given class, what i don't know is
> specifically for methods like each which pass an arg to a given block...
>
> --
> It's easy to play any musical instrument: all you have to do is
> touch the right key at the right time and the instrument will
> play itself. -- J.S. Bach
What you need is "yield".
This does what you need:
class String
def each_char
0.upto(self.length - 1) do |x|
yield self[x,1]
end
end
end
yield passes a value to a block.