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 stringsstr1 = "Edpresso"str2 = "is"str3 = "the"str4 = "best"# get array of charactersa = str1.charsb = str2.charsc = str3.charsd = str4.chars# print the arraysputs "#{a}"puts "#{b}"puts "#{c}"puts "#{d}"
Explanation
-
Lines 1–4: We define four strings,
str1,str2,str3, andstr4. -
Lines 8–11: We split the strings using the
charsmethod of theStringclass. -
Lines 14–17: We output the values to the console.