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

Viewed 109663

I am new to ruby and currently trying to operate on each character separately from a base String in ruby. I am using ruby 1.8.6 and would like to do something like:

"ABCDEFG".each_char do |i|
  puts i
end

This produces a undefined method `each_char' error.

I was expecting to see a vertical output of:

A
B
C
D
..etc

Is the each_char method defined only for 1.9? I tried using the plain each method, but the block simply ouputs the entire string in one line. The only way I figure how to do this, which is rather inconvenient is to create an array of characters from the begining:

['A','B','C','D','...'].each do|i|
  puts i
end

This outputs the desired:

A
B
C
..etc

Is there perhaps a way to achive this output using an unmodified string to begin with?

I think the Java equivalent is:

for (int i = 0; i < aString.length(); i++){
  char currentChar = aString.charAt(i);
  System.out.println(currentChar);
}
6 Answers
"ABCDEFG".chars.each do |char|
  puts char
end

also

"ABCDEFG".each_char {|char| p char}

Ruby version >2.5.1

Returns an array of characters in str. This is a shorthand for str.each_char.to_a. If a block is given, which is a deprecated form, works the same as each_char.

from ruby-doc.org

also now you can do string.chars

Related