Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby idiom for substring from index until end of string

Just wondering if there's a Ruby idiom for extracting a substring from an index until the end of the string. I know of str[index..-1] which works by passing in a range object to the String's [] method but it's a little clunky. In python, for example, you could write str[index:] which would implicitly get you the rest of the string.

Example:

s = "hello world" s[6..-1] # <-- "world" 

Is there anything nicer than s[6..-1]?

like image 786
Sherwin Yu Avatar asked Feb 13 '13 06:02

Sherwin Yu


People also ask

How do you find the substring of a string in Ruby?

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

What does .index do in Ruby?

index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present.


2 Answers

Ruby 2.6 introduced endless ranges, which basically remove the need to have to specify the end index. In your case, you can do:

s = "hello world" s[6..] 
like image 91
vicentazo Avatar answered Sep 20 '22 08:09

vicentazo


I think it isn't.

It seems that Range is better way to do it.

like image 34
Paul Brit Avatar answered Sep 19 '22 08:09

Paul Brit