From: David Alan Black Date: 2002-07-07T23:06:00+09:00 Subject: Re: is there a better string.each? Hello -- On Sun, 7 Jul 2002, Dossy wrote: > On 2002.07.07, Tobias Reif wrote: > > I think String#characters should pass objects of class Character to the > > block. > > > > 'foo'.chars do |char| > > puts char > > end > > # f > > # o > > # o > > That's limiting. What if you wanted an Array of the Character objects? > You'd have to do something like: > > charArray = [] > 'foo'.chars { |char| charArray << char } Not if the return value is an array. This example doesn't include class Character, but you can see the principle: class String def chars split("").each {|c| yield c if block_given?} end end p "abc".chars "abc".chars {|c| puts "char: #{c}"} Output: ["a", "b", "c"] char: a char: b char: c (My approach to #chars may be a little wasteful, as it tests for block for every character, but I like its conciseness :-) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav