Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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 
like image 204
Austin Richardson Avatar asked Aug 31 '10 17:08

Austin Richardson


People also ask

Can you index a string 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. It will return nil if not found.

How do you cut a string in Ruby?

Ruby – String split() Method with Examplessplit is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string.

How do you slice str?

The slice() method extracts a part of a string. The slice() method returns the extracted part in a new string. The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract.


2 Answers

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 -> 
like image 108
Nakilon Avatar answered Sep 29 '22 21:09

Nakilon


Use -1 :-)

'Austin'[1..-1] # => "ustin" 
like image 26
Topher Fangio Avatar answered Sep 29 '22 23:09

Topher Fangio