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

Introduction

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:

Demo

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

Result

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

Related Topic