2011-06-21 2 views

ответ

95

Try foo[0...100], любой ареал сделаю. Диапазоны также могут быть отрицательными. Это well explained in the documentation Руби.

+8

Foo [0,100] является тем же самым. – steenslag

+19

Также обратите внимание, что '' 'foo [0..100]' '' и '' 'foo [0 ... 100]' '' различны. Один - от нуля до ста, а другой - от нуля до девяноста девяти. –

+7

Уточнение выше: foo [0..100] является _inclusive_ (от 0 до 100) и foo [0 ... 100] является _exclusive_ (от 0 до 99) – OneHoopyFrood

16

Используя [] -оператора:

foo[0,100] # Get the first 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 the first 100 characters starting at position 0 
foo.slice(0...100) # All identical to [] 

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

foo[0] # Returns the first character (doh!) 
foo[-100,100] # Get the last 100 characters in order. Negative index is 1-based 
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 
+0

Спасибо за это. Полезно видеть различные нюансы с помощью оператора [], а не просто правильный ответ. – johngraham

+0

Вот как нам нравится наш Рубин. Не только один правильный способ сделать это (TM). –

Смежные вопросы