Ruby - Как выбрать несколько символов из строки - PullRequest
61 голосов
/ 21 июня 2011

Я пытаюсь найти функцию для выбора, например, первые 100 символов строки. В PHP существует функция substr

Имеет ли Ruby похожую функцию?

Ответы [ 2 ]

119 голосов
/ 21 июня 2011

Попробуйте foo[0...100], подойдет любой диапазон.Диапазоны также могут идти в минус.Это хорошо объяснено в документации Ruby.

35 голосов
/ 24 января 2016

Использование оператора [] ( документы ):

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!)

Использование метода .slice ( документы ):

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

И для полноты:

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

Обновление для Ruby 2.6 : Бесконечные диапазоны уже здесь (по состоянию на 2018-12-25)!

foo[0..]      # Get all chars starting at the first. Identical to foo[0..-1]
foo[-100..]   # Get the last 100 characters
...