What is the chars method in Ruby?

Overview

In Ruby, the chars method is a string method that is used to return an array of characters of a string.

Syntax

str.chars

Parameters

str: The string that is split into characters by the chars method.

Return value

This method returns an array of characters.

Code

# create some strings
str1 = "Edpresso"
str2 = "is"
str3 = "the"
str4 = "best"
# get array of characters
a = str1.chars
b = str2.chars
c = str3.chars
d = str4.chars
# print the arrays
puts "#{a}"
puts "#{b}"
puts "#{c}"
puts "#{d}"

Explanation

  • Lines 1–4: We define four strings, str1, str2, str3, and str4.

  • Lines 8–11: We split the strings using the chars method of the String class.

  • Lines 14–17: We output the values to the console.