Ruby-如何从字符串中选择一些字符


Answers:


140

试试看foo[0...100],任何范围都可以。范围也可以为负。Ruby文档中对此进行了很好的解释


25
另请注意,foo[0..100]foo[0...100]是不同的。一个是零到一百,而另一个是零到九十九。
卡利·伍兹

11
上面的说明:foo [0..100]是包含的(0到100),而foo [0 ... 100]是包含的(0到99)
OneHoopyFrood 2015年

2
为了阐明@steenslag的建议,它foo[0,100]也是唯一的
约书亚·品特

40

使用[]-operator(docs):

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

Ruby 2.7的更新无限范围现在在这里(截至2019-12-25),并且可能是“返回数组的第一个xx”的规范答案:

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

使用.slice方法(docs):

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

1
谢谢你 用[]运算符查看不同的细微差别是有帮助的,而不仅仅是正确的答案。
johngraham '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.