With any character string Let's create a method that counts how many "hi" there are and outputs that number.
count_hi('abc hi ho') → 1 count_hi('ABChi hi') → 2 count_hi('hihi') → 2
scan is a method that searches the target element for the character string specified by the argument and returns it as an array.
In most cases, it is used as a regular expression, but it can also be used when you want to search for a string and return it as an array even if it is not a regular expression.
The description method is written as object.scan (regular expression).
qiita.rb
def count_hi(str)
puts str.scan("hi").length
end
Use the scan method for the argument str. This time, I want to count how many "hi" there are, so I output it using the length method, which is a method for checking the length of the character string and the length of the array.
Recommended Posts