As the title suggests, it outputs about the slice method.
The specified element can be extracted from the array or character string.
array = [0,1,2,3,4,5,6]
result = array.slice(1)
puts result
#=> 1
#The array itself does not change
puts array
#=> [0,1,2,3,4,5,6]
You can also retrieve multiple elements.
The following is the method of "taking out ○ pieces from here".
array = [0,1,2,3,4,5,6]
#Slice the elements for sequence numbers 1 to 4
result = array.slice(1,4)
puts result
#=> 1 2 3 4
You can also use this method to:
#Create a method that outputs the last two characters of an arbitrary character string three times repeatedly
def extra_end(str)
num = str.length
right2 = str.slice(num - 2, 2)
puts right2 * 3
end
extra_end(str)
Get the number of characters in the string with str.length
.
Since the character string is the same as the array and the beginning is counted from 0,
To get the last character of a string, use str.slice (num -1)
.
This time I want to get the last two characters of the string, so set it to str.slice (num --2, 2)
.
Another way to retrieve multiple elements There is also a method of "specifying and extracting sequence numbers ○ to X".
array = [0,1,2,3,4,5,6]
#Slice the elements of sequence numbers 1 to 4
result = array.slice(1..4)
puts result
#=> 1 2 3 4
You can also do this.
#Define elements
array = "string"
#Of the sequence number-From 3-Cut out a string in the range of 1
result = array.slice(-3..-1)
puts result
#=> "ing"
The rightmost is -1, and the sequence numbers are counted from right to left as -1, -2, -3 ....
You can change the original array or string by adding! After the slice. (Destructive method)
string = "abcde"
result = string.slice!(2)
puts result
#=> "c"
# "c"Has been removed
puts string
#=> "abde"
Recommended Posts