Ruby - Using block to iterate over the characters in a string


You can use a block to iterate over the characters in a string.

First, you need to split off each character from a string.

This can be done using the split method of the String class like this:

"hello world".split(//)

The split method divides a string into substrings based on a delimiter and returns an array of these substrings.

Here // is a regular talk that defines a zero-length string.

You can iterate over this array of characters, returning a capitalized version of each:


newstr = ""
a = "hello world".split(//).each{ |x| newstr << x.capitalize }
puts a# from w ww  .  ja  v  a  2  s .c o  m
puts newstr


At each iteration, a capitalized character is appended to newstr.

Related Topic