You can learn the slice
method while solving the problem. Previous article summarizes "slice method and slice! Method", so please have a look.
--Practice --Problem --Answer (commentary) --Another solution
--Summary --References
slice
You can extract the specified element from a string or array by using the slice method. Since the subscript starts from 0
, specify the argument in consideration.
Example
array = [0,1,2,3,4,5,6] #Create an array
array.slice(1..3) #1 of the array~Take out the third
#=> [1, 2, 3]
array.slice(1, 5) #Extract 1 to 5 elements of the array
#=> [1, 2, 3, 4, 5]
Create a method that repeats the last two characters of the string three times and outputs it.
answer
def repeat_char(str)
char_length = str.length - 2 #I want to get the length of the string and start from the last two characters-Doing 2
char_slice = str.slice(char_length, 2) #Variable char_Extract 2 characters from length
p char_slice * 3 #Output 3 times
end
#Method call
repeat_char('apple')
repeat_char('orange')
repeat_char('melon')
#Terminal output result
# "lelele"
# "gegege"
# "ononon"
In order to make the start position ** second ** from the end, in the above example, the length of the character string is obtained and then -2
.
Here, it is obtained by specifying -2
as the first argument of slice
.
Another solution
def repeat_char(str)
char_slice = str.slice(-2, 2) #The penultimate start
p char_slice * 3
end
#Method call
repeat_char('apple')
repeat_char('orange')
repeat_char('melon')
--"Slice" can extract the element specified by the argument from a character string or array.
-** The subscript starts from number 0 **, so be careful when taking it out.
--By specifying -1
as the first argument of" slice ", you can" get the last "of any ** character string or array **.
-Ruby 3.0.0 Reference Manual (Array # slice)
-Ruby 3.0.0 Reference Manual (String # slice!)
-What is the slice method? Let's solve the example and understand the difference from slice!
Recommended Posts