Friday, November 09, 2007

Rails: String#each_char

Documentation
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

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

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

1 comment:

  1. Apparently, each_char is misleadingly listed in the 1.8.6 ruby docs, but doesn't work until version 1.8.7.

    See this: http://javazquez.com/juan/2008/06/25/handling-rubys-stringeach_char-iterator/

    ReplyDelete

Note: Only a member of this blog may post a comment.