44

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]?

Sherwin Yu
  • 3,180
  • 2
  • 25
  • 41

6 Answers6

10

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..]
vicentazo
  • 1,739
  • 15
  • 19
7

I think it isn't.

It seems that Range is better way to do it.

Paul Brit
  • 5,901
  • 4
  • 22
  • 23
  • 2
    Sorry, could you clarify? You think ```Range``` (the way I have in the question) is the best way to do it? – Sherwin Yu Feb 13 '13 at 06:48
7

Here is 'nicer' if you wish. You can extend ruby String class and then use this method into your code. For example:

class String
  def last num
    self[-num..-1]
  end
end

And then:

s = "hello world"
p s.last(6)
Yevgeniy Anfilofyev
  • 4,827
  • 25
  • 27
5

To get the string from a range:

s = 'hello world'
s[5..s.length - 1] # world

However, if you just want to get the last word:

'hello world'.split(' ').last # world
Simon Tsang
  • 127
  • 1
  • 3
  • 8
2

You can extend the String class. Not sure if it's a ruby idiom though:

class String
  def last(n)
    self[(self.length - n)..-1]
  end
end
Flauwekeul
  • 869
  • 7
  • 24
1

Rails' activesupport library (which can be installed as a gem independent of Rails) adds a from method to strings:

> s = "hello world"
"hello world"
> s.from(6)
"world"

https://api.rubyonrails.org/classes/String.html#method-i-from

MothOnMars
  • 2,229
  • 3
  • 20
  • 23