首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Ruby -如何从字符串中选择一些字符

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

Stack Overflow用户
提问于 2011-06-21 18:41:32
回答 2查看 89.1K关注 0票数 79

我正在尝试寻找一个函数来选择字符串的前100个字符。在PHP中,存在substr function

Ruby有类似的功能吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-21 18:43:26

尝试foo[0...100],任何范围都可以。范围也可以变为负数。它是Ruby的well explained in the documentation

票数 148
EN

Stack Overflow用户

发布于 2016-01-24 17:46:57

使用[]-operator (docs):

代码语言:javascript
复制
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!)

Update for Ruby 2.7Beginless ranges现在在这里(截至2019-12-25),可能是“返回数组的第一个xx”的标准答案:

代码语言:javascript
复制
foo[...100]  # Get all chars from the beginning up until the 100th (exclusive)

使用.slice方法(docs):

代码语言:javascript
复制
foo.slice(0, 100)  # Get 100 characters starting at position 0
foo.slice(0...100) # Behaves the same as operator [] 

为了完整性:

代码语言:javascript
复制
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

Update for Ruby 2.6Endless ranges现在就在这里(截至2018-12-25)!

代码语言:javascript
复制
foo[0..]      # Get all chars starting at the first. Identical to foo[0..-1]
foo[-100..]   # Get the last 100 characters
票数 44
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6423966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档