Iterate chars in a string

Robert K. wrote:

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

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

So it does! Well I learnt something anyway :slight_smile:

a = “ook\nook\tEeek!\n”
a.scan(/.|\s/) { |c| p c }
“o”
“o”
“k”
“\n”
“o”
“o”
“k”
“\t”
“E”
“e”
“e”
“k”
“!”
“\n”

(quick fix, and now handles tabs|spaces|new lines)

Kev

Hello World

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

Cheers
Robert

On 3/20/06, James Edward G. II [email protected] wrote:

a.scan(/./) { |c| p c }
“o”


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/

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

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 G. 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.