__ I want to cut out only a specific part from a character string. At that time __
By using the slice method, the specified element can be extracted from the array or character string.
#Create an array
array = [0,1,2,3,4,5,6]
#Slices the element specified by the argument from the array
ele1 = array.slice(1)
puts ele1
#=> 1
#Slice the elements for array numbers 1 to 4
ele2 = array.slice(1,4)
puts ele2
#=> 1 2 3 4
#The array remains the same
puts array
#=> [0,1,2,3,4,5,6]
Create a method that outputs the last two characters from an arbitrary character string.
extra_end('Hello') → 'lo'
extra_end('abcde') → 'de'
Here, the method to be called is extra_end
.
Now let's write the code.
def extra_end(str)
char_num = str.length
right2 = str.slice(char_num - 2, 2)
puts right2
end
First, let the formal argument of extra_end be str
and prepare to receive the actual argument.
char_num
is defined using the length method to get the number of characters in str
.
The problem this time is "get the last 2 characters", so use the slice method to set it to -2 of char_num
, that is, go back two characters counting from the back, and then set it to 2, and then two characters from there. Get the minutes.
For example, if you call the method with extra_end ('Hello'), char_num = 5 and right2 = str.slice (3,2).
slice (3,2) cuts two elements counting from the third array number (index). In this case, the cut result lo remains, and right2 = lo.
■ Reference reference
Recommended Posts