Create a method that can retrieve characters from any location

【Overview】

1. Conclusion </ b>

2. How to describe </ b>

3. What I learned from here </ b>

  1. Conclusion

Use the length and slice methods </ b>!


2. How to describe

def srt_search(strings)
  character_number = strings.length #---❶
  character_reslut = strings.slice(character_number - 3, 3) #---❷
end

I wrote it as above!

In ❶ length, the character string was changed to a number.

ex) Convert to "Good job" ➡︎ "8" characters

❷ Since we want the number from the last to the third this time, we can get the number of "-3" characters from the number of characters from character_number by doing slice (character_number --3, 3) from the number of characters in ❶.

ex) If you "-3" from the 8 characters of "Good job", the "3" character of the "5" th (= 3rd from the end) from the beginning is extracted.

Referenced URL: [Ruby Primer] Explanation about ruby slice
3. What I learned from here

The slice (character_number --3, 3) part is I thought that if you use slice (-3,3), you can always take the 3rd character from the end. However, it should be noted that when it comes to the composition of sentences (ex: Hi, John! Nice to meet you!), Slice will judge by word division and "to meet you!" Will be extracted.

Recommended Posts