logo       

[jruby-user] Iterating over characters in a String ?: msg#00142

lang.jruby.user

Subject: [jruby-user] Iterating over characters in a String ?

I'm looking for some way to iterate over the characters of a String in
Ruby. Ruby's class String does not provide a method each_char, nor
does JRuby's class String. Instead, both provide method each_byte.

Now, Ruby does not do Unicode. What a shame for a language developed
in Japan ! Instead, it believes that the size of a char is 8
bits. Thus, Ruby thinks that Matz' name, which is 松本行弘, has 12
characters:

matz = '松本行弘'
matz.length -> 12

Help. How do I translate the following Java method into JRuby ?

void m(String s) {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
}

The following does *not* work in Ruby, because it outputs each byte,
instead of each letter.

def each_char(str)
0...str.length do |i| puts str[i] end
end
<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise