2011-06-21 26 views

Odpowiedz

95

Wypróbuj foo[0...100], dowolny zakres zrobi. Zakresy mogą również ujemne. Jest to well explained in the documentation z Ruby.

+8

foo [0100], jest taka sama. – steenslag

+19

Należy również zauważyć, że '' 'foo [0..100]' '' i '' 'foo [0 ... 100]' '' są różne. Jedna wynosi od zera do stu, a druga od zera do dziewięćdziesięciu dziewięciu. –

+7

Wyjaśnienie powyżej: foo [0..100] to _inclusive_ (0 do 100) i foo [0 ... 100] jest _jednoznaczne_ (0 do 99) – OneHoopyFrood

16

Stosując [] -operator:

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) 

Stosując .slice metody:

foo.slice(0, 100) # Get the first 100 characters starting at position 0 
foo.slice(0...100) # All identical to [] 

i kompletności:

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

Dzięki za to. Przydatne jest zobaczenie różnych niuansów za pomocą operatora [], a nie tylko właściwej odpowiedzi. – johngraham

+0

Tak właśnie lubimy naszą Ruby. Nie tylko jeden właściwy sposób na to (TM). –