Ruby string slice index: str[n..infinity]

Ruby

Ruby Problem Overview


Easy question, but couldn't find it in the doc.

How do I slice a string or array from n until forever?

>> 'Austin'[1..3]
=> "ust"
>> 'Austin'[1..]
SyntaxError: compile error
(irb):2: syntax error, unexpected ']'
    from (irb):2

Ruby Solutions


Solution 1 - Ruby

Use reverse indexing:

[1..-1]

An element in Ruby (and some other languages) has straight forward index and a "reversed" one. So, string with length n has 0..(n-1) and additional (-n)..-1 indexes, but no more -- you can't use >=n or <-n indexes.

  'i' 'n'|'A' 'u' 's' 't' 'i' 'n'|'A' 'u' 's' 't' 'i' 'n'|'A' 'u' 's'
  -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7   8 
<- error |                you can use this               | error ->

Solution 2 - Ruby

Use -1 :-)

'Austin'[1..-1] # => "ustin"

Solution 3 - Ruby

Pretty elegant using the endless range introduced in Ruby 2.6:

string = 'Austin'
string[1..] # => ustin

Hope that's handy for someone. Cuts a couple of characters from the best approach until now, and will be very readable once endless ranges are regularly adopted.

Solution 4 - Ruby

If you assign the string to a variable, you can use length/size

string = 'Austin'
string[1..string.length]  # => ustin
string[1..string.size]    # => ustin

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAustin RichardsonView Question on Stackoverflow
Solution 1 - RubyNakilonView Answer on Stackoverflow
Solution 2 - RubyTopher FangioView Answer on Stackoverflow
Solution 3 - RubySRackView Answer on Stackoverflow
Solution 4 - RubyJason NobleView Answer on Stackoverflow