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

use*_*705 66 ruby string function char substr

我试图找到一个函数选择例如字符串的前100个字符.在PHP中,存在substr 函数

Ruby有一些类似的功能吗?

Sor*_*row 125

尝试foo[0...100],任何范围都可以.范围也可以消极.Ruby 的文档中对此进行了详细解释.

  • 还要注意````foo [0..100]```和```foo [0 ... 100]```是不同的.一个是零到一百,而另一个是零到九十九. (24认同)
  • 澄清如上:foo [0..100]是_inclusive_(0到100),foo [0 ... 100]是_exclusive_(0到99) (11认同)
  • foo [0,100]是一样的. (9认同)
  • 为了澄清@ steenslag的建议,`foo [0,100]`也是_exclusive_. (2认同)

Chr*_*bek 37

使用[]-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!)
Run Code Online (Sandbox Code Playgroud)

使用.slice方法(docs):

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

为了完整性:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)