Ruby Tuesday – String#each_char

Today’s Ruby Tuesday covers String#each_char.

String#each_char takes a block, and passes each character in the string to the block.

"hello".each_char{|char| print char.upcase}; puts
# HELLO
# => nil

Note that String#each_char does not modify the original string, and that any intended side effects done in the block must be captured some how if desired.

"hello".each_char{|char| char.upcase}
=> "hello"

If the string is empty, the block is never invoked, as there are no characters in the string to call the block with.

"".each_char{|char| puts "xxx"}; puts "done"
# done
# => nil

If no block is given, String#each_char returns an enumerator, which opens up all of the other methods that Enumerable provides.

"hello".each_char.map{|char| char.upcase}.join
# => "HELLO"
"hello".each_char.select{|char| ["a", "e", "i", "o", "u"].include?(char)}.join
# => "eo"
 "hello".each_char.reject{|char| ["a", "e", "i", "o", "u"].include?(char)}.join
# => "hll"

But then again, String provides a method chars which returns all of the characters in the string as an array.

"hello".chars
# => ["h", "e", "l", "l", "o"]
"".chars
# => []

Which means we also get the full Enumerable on that as well.

"hello".chars.select{|char| ["a", "e", "i", "o", "u"].include?(char)}.join
# => "eo"
"hello".chars.reject{|char| ["a", "e", "i", "o", "u"].include?(char)}.join
# => "hll"