[RUBY] scan method problem

problem

With any character string Let's create a method that counts how many "hi" there are and outputs that number.

Output example

count_hi('abc hi ho') → 1 count_hi('ABChi hi') → 2 count_hi('hihi') → 2

use scan

scan is a method that searches the target element for the character string specified by the argument and returns it as an array.

How to use scan

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).

Question answer

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

scan method problem
[Ruby] Search problem using index method
[N + 1 problem]
Java method
to_i method
java (method)
getRequestDispatcher () method
merge method
FizzBuzz problem
Map method
include method
Abstract method
initialize method
List method
puts method
Java method
Class method
Ruby problem ⑦
save! method
getParameter method
[Java] method
private method
rails method
[Java] method