Re: iterate chars in a string

shinya [mailto:[email protected]]:

#I’m a ruby newbie, and I’m searching for a way to iterate
#every char in
#a string, but I cannot find any easy way. My problem is to
#look at every
#char in a string and match it with some known letter.
#I use the String#each_byte iterator for now, but it still be a poor
#solution :confused:

me too, i use each_byte

irb(main):098:0> “test”.each_byte{|b| puts(b.to_s+" → "+b.chr) }
116 → t
101 → e
115 → s
116 → t
=> “test”

i like each_byte when i access like C or raw…

maybe you want something like #each_char

prompt>cat a1.rb
x=“test\ntest2”

class String
def each_char
each_byte do |b|
yield b.chr
end
end
end

x.each_char {|c| puts c}

prompt>ruby a1.rb
t
e
s
t

t
e
s
t
2

hth.
kind regards -botp

On Dec 20, 2005, at 5:29 AM, Peña, Botp wrote:

me too, i use each_byte
maybe you want something like #each_char
end
e
s
t
2

hth.
kind regards -botp

Careful, a character isn’t necessarily a byte in length. You gotta be
aware of $KCODE.