iterating over each character of a String in ruby 1.8.6 (each_char)

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

ABCDEFG.split().each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split().each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

ABCDEFG.each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

Extending la_f0kas comment, esp. if you also need the index position in your code, you should be able to do

s = ABCDEFG
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

iterating over each character of a String in ruby 1.8.6 (each_char)

ABCDEFG.chars.each do |char|
  puts char
end

also

ABCDEFG.each_char {|char| p char}

Ruby version >2.5.1

Leave a Reply

Your email address will not be published.