Yields a single-character string for each character in the string. When $KCODE = ‘UTF8’, multi-byte characters are yielded appropriately.Usage
The String#each_char method is nice for iterating through a string, one character at a time. I generally use regex for string manipulation; however, when context within the string matters, each_char is helpful.
Test
unit_tests do
test "each_char can be used to strip every other charater" do
strip, result = true, ""
"hello world".each_char do |char|
result << char if strip
strip = !strip
end
assert_equal "hlowrd", result
end
end
Apparently, each_char is misleadingly listed in the 1.8.6 ruby docs, but doesn't work until version 1.8.7.
ReplyDeleteSee this: http://javazquez.com/juan/2008/06/25/handling-rubys-stringeach_char-iterator/