The split method is a method that "separates character strings one by one and makes them into an array".
def split_1st(string) #Method that expects string as an argument
string.split("") #to_Note that there is no s method.
end
p split_1st("12345")
#=> ["1","2","3","4","5"]
p split_1st("Thank You")
#=> ["T","h","a","n","k"," ","Y","o","u"]
If a space is included like "Thank You", the space is also regarded as one of the character strings and output.
What if the argument is a number rather than a string? If you add the to_s method as shown below, you can also separate the numbers into an array.
def split_2nd(integer) #A method that expects an integer as an argument
integer.to_s.split("") #to_Convert the numerical value to a character string with the s method, and separate the character strings one by one with the split method.
end
p split_2nd(12345)
#=> ["1","2","3","4","5"]
p split_2nd("12345") #This call to the original string is also validly printed.
#=> ["1","2","3","4","5"]
Recommended Posts