views:

364

answers:

2

Hello,

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);
}

Many thanks in advace.

+5  A: 

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
yjerem
Thanks for the helpful tip. It works fine. So what is the each_char method used for? Just for the newer version I suppose?
denchr
I haven't looked into it until now, but after Googling a bit, apparently it is mistakenly listed in the 1.8.6 docs but isn't available until 1.8.7.
yjerem
The each_char method is for the *older* version, which doesn't otherwise have it. Not yet documented at http://ruby-doc.org/core/classes/String.html#M000862 and to my surprise, I see that each_char yields a string, like jeremy's split.
+1  A: 

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'
kaka2008
I didn't know that - thanks! +1
Mike Woodhouse