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]
?
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.
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.
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..]
I think it isn't.
It seems that Range
is better way to do it.
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