By Alvin Alexander. Last updated: June 4, 2016
Ruby character/string FAQ: How can I loop through each character in a Ruby String, and perform some operation on each character?
I'm currently using Ruby 1.8.6, and you can use the Ruby each_char method if you'll first require
the jcode
module. To be clear, this code will not work in Ruby 1.8.6:
a = 'hello, world' a.each_char { |c| puts c }
In fact it results in the following error:
each-char.rb:4: undefined method `each_char' for "hello, world":String (NoMethodError)
However, if you first require the jcode
library, the following code will work:
require 'jcode' a = 'hello, world' a.each_char { |c| puts c }
For the record, that code generates the following output:
h e l l o , w o r l d
Discussion
This feature may be modified in future versions of Ruby, but that's the way it works today. Here's a link to a brief discussion about this issue.