tags:

views:

64

answers:

4

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
+2  A: 

Use -1 :-)

'Austin'[1..-1] # => "ustin"
Topher Fangio
+5  A: 

Use reverse indexing:

[1..-1]

Elements in Ruby and some other languages has straight forward indexing and reverse (I can do mistake in terminology). 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 ->
Nakilon
Ah, I thought that would be cheating. Thanks.
Austin
+1 for the illustration
bta
Nice illustration, however, your use of "valid" letters (i.e. ones existing in the string) is a bit misleading in my opinion since data outside the bounds of the string are really undefined. That could be anything, including non-characters. Anyway, +1 for such a well-explained answer :-)
Topher Fangio
+1  A: 

Try using [1..-1]

Vivin Paliath
A: 

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
Jason Noble