In this article, I will explain how to extract an arbitrary character string in Ruby. It also explains the behavior when a negative number is specified as an argument when extracting a character string.
The code itself looks like this: By specifying the 0th to 2nd characters in the character string, the 3rd character from the beginning is output.
def left2(str)
puts str[0..2]
end
left2('Hello')
--Execution result--
Hel
Now let's set the second argument of str to -1.
def left2(str)
puts str[0..-1]
end
left2('Hello')
--Execution result--
Hello
All the characters were taken out and it was output as Hello. The reason is that -1 represents the end of the string. This is the result because we are extracting from the 0th to the end of the string. The table shows which character each character corresponds to.
letter | For positive numbers | For negative numbers |
---|---|---|
H | 0th character | -5th character |
e | 1st character | −4th character |
l | 2nd character | -3rd character |
l | 3rd character | −2nd character |
o | 4th character | -1st character |
According to the table above, if you set the first argument to 1 and the second argument to -4, Since the 0th and 1st characters are extracted, the result is assumed to be "He". Let's do it right away.
def left2(str)
puts str[0..-4]
end
left2('Hello')
·Execution result
% ruby test.rb
He
It became "He" as expected. The point of this article is that negative values can be used as arguments when retrieving strings.
Recommended Posts