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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (40)

我想找到一个函数,例如字符串的前100个字符。在PHP中,存在substr 函数

Ruby有一些类似的功能吗?

提问于
用户回答回答于
用户回答回答于

使用[]-运算符:

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

扫码关注云+社区

领取腾讯云代金券