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
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.
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.
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.
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 ->
Use -1 :-)
'Austin'[1..-1] # => "ustin"
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