The each_char
in Ruby is used to pass each character that makes a string to a each_char
takes a single parameter which represents characters in a string.
str.each_char {|c| block }
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
.
It returns the characters of a string.
# create a stringstr1 = "Edpresso"# print each character# using each_char methodstr1.each_char {|c| puts c}
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.