I am reviewing the drill to strengthen my logical thinking. As a beginner, I would appreciate it if you could let me know if you have any questions.
For any string, use the slice method to erase the nth character, Let's create a method that outputs the character string with the nth character erased.
missing_char(string, num)
missing_char ('Genghis Khan', 1) →'Nghis Khan' missing_char ('Genghis Khan', 2) →'Jigisukan' missing_char ('Genghis Khan', 4) →'Genghis Khan'
slice You can extract the specified element from an array or character string. When specifying the element of the character string, use a number, and the first character string is counted from 0.
slice! ~~ A method with an exclamation mark (!) At the end is called a destructive method. A method that changes the original array or string. ~~ !! It is not the only way to distinguish between destructive and non-destructive. Many are paired, but that's not a Ruby rule. This ↓ was a great learning experience. The presence or absence of! In a Ruby method name does not mean destructive / non-destructive
The slice! method can remove the specified element.
def missing_char(str, n)
str.slice!(n - 1)
puts str
end
#call
missing_char('Genghis Khan', 1)
#result
'Ngiscan'
This time, I want to output the character string with the nth character erased, so I will use the slice! Method with exclamation (!).
The flow is explained in the model answer as follows. ① At the caller, give an instruction to erase the "1" first character of "Genghis Khan". (2) "Genghis Khan" is passed to str and "1" is passed to the formal argument of n. ③ Erase the "1st" character of "Genghis Khan" in str with slice!
One thing to note here is the (n -1)
next to slice !.
As mentioned in the hint, the first string is counted from 0.
Therefore, if you do not do -1, the first "n" of "Genghis Khan" will be erased and it will become "" Jigisukan "".
So
str.slice!(n - 1)
By doing, you can erase the characters you really want to erase from str.
Recommended Posts