Forum: Ruby Re: iterate chars in a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
=?iso-8859-1?Q?Pe=F1a=2C_Botp?= (Guest)
on 2005-12-20 12:29
(Received via mailing list)
shinya [mailto:removed_email_address@domain.invalid]:

#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 :/

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
Logan C. (Guest)
on 2005-12-20 12:44
(Received via mailing list)
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.
This topic is locked and can not be replied to.