When the following problem is raised, I will leave it as a memorandum because it was wrong. **【problem】 Create a method that counts how many arbitrary strings exist and outputs that number **
I have answered the following.
Ruby
def count_hi(word)
puts word.count('hi')
end
word = "hi!hideyuki. hidemi."
count_hi(word)
Originally, "3" is the correct answer, but in the above description, it becomes "8": expressionless:
Ruby
def count_hi(word)
puts word.scan('hi').length
end
word = "hi!hideyuki. hidemi."
count_hi(word)
In the above description, "8" is displayed: relaxed:
** count ** counts the number of "h" and "i" instead of "hi".
** scan ** returns an array of matched substrings. Therefore, if there is no ** length **, the display will be as follows.
Ruby
puts word.scah('hi')
#hi hi hi is displayed
** length ** originally returns the number of characters in the string, but by setting it to word.scan ('hi'). ** length **, the array returned by scan will be counted.
Counting the number of occurrences of a specific character --Ruby Tips! String # count (Ruby 2.7.0 Reference Manual) --Ruby-lang String # scan (Ruby 2.7.0 Reference Manual) --Ruby-lang String # length (Ruby 2.7.0 Reference Manual) --Ruby-lang
Recommended Posts