Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 455
user1011444 Avatar asked Dec 22 '25 11:12

user1011444


2 Answers

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#[]

like image 140
Charles Caldwell Avatar answered Dec 24 '25 02:12

Charles Caldwell


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

string = "Yellow"
puts string[1..-1] -> outputs "ellow"
like image 41
SirDarius Avatar answered Dec 24 '25 04:12

SirDarius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!