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.
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.
Documentation for String#[]
You should use -1 as right boundary in your interval:
string = "Yellow"
puts string[1..-1] -> outputs "ellow"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With