Ruby - How to select some characters from string Ruby - How to select some characters from string ruby ruby

Ruby - How to select some characters from string


Try foo[0...100], any range will do. Ranges can also go negative. It is well explained in the documentation of Ruby.


Using the []-operator (docs):

foo[0, 100]  # Get 100 characters starting at position 0foo[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!)

Update for Ruby 2.7: Beginless ranges are here now (as of 2019-12-25) and are probably the canonical answer for "return the first xx of an array":

foo[...100]  # Get all chars from the beginning up until the 100th (exclusive)

Using .slice method (docs):

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

And for completeness:

foo[0]         # Returns the indexed character, the first in this casefoo[-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 -1foo[-100..-1]  # Get the last 100 characters in orderfoo[-1..-100]  # Get the last 100 characters in reverse orderfoo[-100...foo.length] # No index for one beyond last character

Update for Ruby 2.6: Endless ranges are here now (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