Reputation: 1399
string = "Yellow"
puts string[1..string.length] -> outputs "ellow"
Is there a shorter way to get Ruby to do the same thing without using string.length? In Python, for example, we can write string[1:] and it will do it.
Thanks in advance.
Upvotes: 2
Views: 880
Reputation: 17169
While using []
in Ruby to get the index of a String or an Array, using a negative number will start the counting from the end of the index starting with 1
([-0]
will get you the same as [0]
).
In your example,
puts string[1..-1]
will output the desired string "ellow"
.
Equally,
puts string[1..-2]
will produce "ello"
and so on.
Upvotes: 8
Reputation: 42889
You should use -1 as right boundary in your interval:
string = "Yellow"
puts string[1..-1] -> outputs "ellow"
Upvotes: 2