user1011444
user1011444

Reputation: 1399

How to select a part of a string from a beginning index to the very end in Ruby?

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

Answers (2)

Charles Caldwell
Charles Caldwell

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.

Documentation for String#[]

Upvotes: 8

SirDarius
SirDarius

Reputation: 42889

You should use -1 as right boundary in your interval:

string = "Yellow"
puts string[1..-1] -> outputs "ellow"

Upvotes: 2

Related Questions