Iterate chars in a string

You mean besides the fact that it's not very Rubyish? <laughs> Seriously, it seems fine, though I prefer each_byte() or scan(/./m).

James Edward Gray II

···

On Dec 20, 2005, at 3:35 PM, Dirk Meijer wrote:

i've always used this:

0.upto(string.length-1) do |n|
    p string[n,1]
end

anything wrong with this?

Kev Jackson wrote:

a = "ook\nook\tEeek!\n"
a.scan(/.|\s/) { |c| p c }

a.scan(/./m) {|c| p c } # m is for multi-line

Cheers,
Dave

Hello World

"I am puzzled".each_byte do |b| puts "%c" % b ;end

Cheers
Robert

···

On 3/20/06, James Edward Gray II <james@grayproductions.net> wrote:

On Mar 20, 2006, at 3:38 AM, Robert Klemme wrote:

> Kev Jackson wrote:
>> Robert Klemme wrote:
>>> Lyndon Samson wrote:
>>>
>>>> a="123"
>>>>
>>>> 0.upto(a.length) { |i| puts a[i..i] }
>>>
>>>
>>> Alternatively:
>>>
>>> a.length.times {|i| puts a[i].chr}
>>>
>>> Many roads to Rome...
>>>
>>> robert
>>>
>> or even
>> a.scan(/./) { |c| p c }
>
> We had that already: your version ignores newlines. :slight_smile:

>> require "jcode"
=> true
>> "Hello\nWorld!".each_char { |chr| p chr }
"H"
"e"
"l"
"l"
"o"
"\n"
"W"
"o"
"r"
"l"
"d"
"!"
=> "Hello\nWorld!"

James Edward Gray II

--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein

"I am puzzled".each_byte { |b| puts b.chr }

I'm surprised that not many people knew about 'each_byte()'. Maybe it's a problem with Ruby docs? Or maybe it is just counter-intuitive - I would expect each() iterate over bytes, and provide each_lines() to iterate over lines instead.

Mike

http://www.rubycentral.com/ref/

Robert Dober wrote:

···

Hello World

"I am puzzled".each_byte do |b| puts "%c" % b ;end

Cheers
Robert

On 3/20/06, James Edward Gray II <james@grayproductions.net> wrote:

On Mar 20, 2006, at 3:38 AM, Robert Klemme wrote:

Kev Jackson wrote:

Robert Klemme wrote:

Lyndon Samson wrote:

a="123"

0.upto(a.length) { |i| puts a[i..i] }

Alternatively:

a.length.times {|i| puts a[i].chr}

Many roads to Rome...

    robert

or even
a.scan(/./) { |c| p c }

We had that already: your version ignores newlines. :slight_smile:

require "jcode"

=> true

"Hello\nWorld!".each_char { |chr| p chr }

"H"
"e"
"l"
"o"
"\n"
"W"
"o"
"r"
"l"
"d"
"!"
=> "Hello\nWorld!"

James Edward Gray II

each_bytes is not a good way to do this, btw. It will not remain
compatibile with Ruby 2.0. And using enumerator is a pretty heavy
solution. Then there's this...

  require 'facet/string/chars'

Source code for chars.rb:

  class String

    # Returns an array of characters.

···

#
    # "abc".chars #=> ["a","b","c"]
    #
    def chars
      self.split(//)
    end

  end

T.