** How to call ** missing_char(string, num)
** Output example: ** missing_char('kitten', 1) → 'itten' missing_char('kitten', 2) → 'ktten' missing_char('kitten', 4) → 'kiten'
#Create a string
string = "abcdefg"
#Get the element specified by the argument from the character string and assign it to the variable
str = string.slice(2)
#Output the character string assigned to str
puts str
#=> "c"
#The string remains as it is
puts string
#=> "abcdefg"
string = "abcdefg"
str = string.slice!(2)
puts str
#=> "c"
# "c"Has been removed
puts string
#=> "abdefg"
def missing_char(str, n)
str.slice!(n - 1)
puts str
end
Use the ** slice! Method ** to strip the value obtained from the string itself to erase the nth character for any character. However, since the ** slice method ** cannot change the shape of the character string itself, it is changed to the ** slice! method ** with an exclamation (!).
This slice! method does the processing inside the missing_char method and The argument str of the missing_char method is the input character string, and n is a mechanism to enter a number that indicates which character string to delete. And the slice! method takes the number obtained by subtracting 1 from n as an argument. Why subtract 1? Even when specifying the order of character strings, the first character string is counted from 0, just like an array.
[Order of character strings](Human 123 s t r 012 [Order of subscripts](Machine
The order of letters seen by humans is 1 to The order of letters seen from the machine is 0 to Since it is a translation from human to machine, I could understand it with the feeling of "n -1". It's deep.
Recommended Posts