Ruby - How to select multiple characters from a string

I am trying to find a function to select, for example, the first 100 characters of a string. PHP has a substr function

Does Ruby have a similar feature?

+65
function string ruby char substr chars
Jun 21 '11 at 10:41
source share
2 answers

Try foo[0...100] , any range will work. Ranges can also be negative. This is well explained in the Ruby documentation .

+125
Jun 21 2018-11-11T00:
source share

Using [] -operator ( documents ):

 foo[0, 100] # Get 100 characters starting at position 0 foo[0..99] # Get all characters in index range 0 to 99 (inclusive!) foo[0...100] # Get all characters in index range 0 to 100 (exclusive!) 

Using the .slice ( docs ) method:

 foo.slice(0, 100) # Get 100 characters starting at position 0 foo.slice(0...100) # Behaves the same as operator [] 

And for completeness:

 foo[0] # Returns the indexed character, the first in this case foo[-100, 100] # Get 100 characters starting at position -100 # Negative indices are counted from the end of the string/array # Caution: Negative indices are 1-based, the last element is -1 foo[-100..-1] # Get the last 100 characters in order foo[-1..-100] # Get the last 100 characters in reverse order foo[-100...foo.length] # No index for one beyond last character 

Update for Ruby 2.6 : infinite ranges are already here (as of 2018-12-25)!

 foo[0..] # Get all chars starting at the first. Identical to foo[0..-1] foo[-100..] # Get the last 100 characters 
+37
Jan 24 '16 at 9:46
source share



All Articles