【问题标题】:Ruby - How to select some characters from stringRuby - 如何从字符串中选择一些字符
【发布时间】:2011-09-19 10:03:54
【问题描述】:

我正在尝试找到一个用于选择的功能,例如字符串的前 100 个字符。在 PHP 中,存在 substr function

Ruby 有类似的功能吗?

【问题讨论】:

    标签: ruby string function char substr


    【解决方案1】:

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

    【讨论】:

    • 还要注意foo[0..100]foo[0...100] 是不同的。一个是零到一百,另一个是零到九十九。
    • 以上澄清:foo[0..100] 是 inclusive(0 到 100),而 foo[0...100] 是 exclusive i>(0 到 99)
    • 为了澄清@steenslag 的建议,foo[0,100] 也是独家
    【解决方案2】:

    使用[]-运算符(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!)
    

    Update for Ruby 2.7: Beginless ranges 现在在这里(截至 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
    

    Update for Ruby 2.6:Endless ranges 现在在这里(截至 2018 年 12 月 25 日)!

    foo[0..]      # Get all chars starting at the first. Identical to foo[0..-1]
    foo[-100..]   # Get the last 100 characters
    

    【讨论】:

    • 谢谢。查看 [] 运算符的不同细微差别很有帮助,而不仅仅是正确的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多