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.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources