What is each_char in Ruby?

Overview

The each_char in Ruby is used to pass each character that makes a string to a blockA block is a loop in Ruby. in Ruby. The block of each_char takes a single parameter which represents characters in a string.

Syntax

str.each_char {|c| block }

Parameters

str: The string we want to print each of its characters.

c: This is passed to the block. It represents the characters in string str.

Return value

It returns the characters of a string.

Example

# create a string
str1 = "Edpresso"
# print each character
# using each_char method
str1.each_char {|c| puts c}

Explanation

In the code above, we print each character of string str1 using the each_char method. From the result above, we see that the each_char method is used to pass each character of a string to a given block. And in turn, we can do anything to these characters. In this case, we print each of the characters.

Free Resources