在 ruby 1.8.6(each_char)中迭代 String 的每个字符

我是 Ruby 的新手,目前正尝试分别操作 Ruby 中的每个字符和基本字符串。我正在使用 ruby 1.8.6,并且想要做一些类似于:

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

这会产生一个未定义的方法‘ each _ char’错误。

我期望看到一个垂直输出:

A
B
C
D
..etc

each_char方法是否只为1.9定义?我尝试使用普通的 each方法,但是这个块只是在一行中输出整个字符串。我想到的唯一方法是从一开始就创建一个字符数组,这是相当不方便的:

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

这就产生了预期的结果:

A
B
C
..etc

是否有一种方法可以使用一个未修改的字符串来实现这个输出?

我认为 Java 的等价物是:

for (int i = 0; i < aString.length(); i++){
char currentChar = aString.charAt(i);
System.out.println(currentChar);
}
110710 次浏览

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

there is really a problem in 1.8.6. and it's ok after this edition

in 1.8.6,you can add this:

requre 'jcode'

But now you can do much more:

a = "cruel world"


a.scan(/\w+/)        #=> ["cruel", "world"]


a.scan(/.../)        #=> ["cru", "el ", "wor"]


a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]


a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

Extending la_f0ka's 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.

"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