Ruby – 如何从string中select一些字符

我正在试图find一个函数,例如string的前100个字符。 在PHP中,存在substr 函数

Ruby有一些类似的function吗?

尝试foo[0...100] ,任何范围都可以。 范围也可以消极。 这在 Ruby 的文档中有很好的解释 。

使用[] -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) 

使用.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 
Interesting Posts