2011-06-21 62 views

回答

95

尝试foo[0...100],任何范围都可以。范围也可以消极。 Ruby的well explained in the documentation

+8

foo的[0100]是相同的。 – 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

这就是我们如何喜欢我们的Ruby。不只是一个正确的做法(TM)。 –