I would like to find out what character "get" appears from the left in any character string and output the number.
An example output is
count_code("getexxcode")
=>1
count_code("aaagetbbb")
=> 4
count_code("cozexxget")
=> 7
Create a method using the index method. reference: Ruby 3.0.0 Reference Manual: index method
Example of use:
str.index(The character string you want to search,Where to start the search)
First, create a method.
def count_code(str)
end
I would like to use the index method in it to output as shown in the output example.
def count_code(str)
puts str.index("get", 0 )
end
You can now output. However, if nothing is done, it will not look like the output example, and the result will be as follows.
count_code("getexxcode")
=> 0
count_code("aaagetbbb")
=> 3
count_code("cozexxget")
=> 6
Finally,
def count_code(str)
puts str.index("get", 0 ) + 1
end
By giving as, it becomes like the output example.
Recommended Posts