[RUBY] I want to output the character number from the left where an arbitrary character string appears.

【Overview】

1. Conclusion </ b>

2. How to use </ b>

3. What I learned from here </ b>

  1. Conclusion

Use the index method </ b> and puts </ b>!

  1. How to use

python


def search(str)
 puts(str.index("Any character string you want to search")+1)
end

Will be! By doing this, (str) is a formal argument, and an arbitrary character string (actual argument) is fetched, and the return value (contents of puts) is output.

str.index ("Any character string you want to search", [Start position you want to search]) </ b> Is the mold.

There are two things I would like you to be aware of here. This is the part where "+1" is added to the first point </ b>. As with arrays, counts start at "0". Only the first character responds to the second point </ b>.

ex) ohmygoodness,oh! If so, "0" will be output when searching for "oh" (first point). And the second "oh" is not recognized (second point).

  1. What I learned from here

If there is "from the left", it is also from the right. In that case, use "rindex". There are two things to note. The first point is that the [Start position you want to search] is a negative number. Describe as "-1" and "-2". The second point is that the output value is the value counted from the beginning. Also, this also means that only the first character responds (this time only the last oh).

Referenced site: How to search for a character string in Ruby: index, rindex

Recommended Posts