【问题标题】:Getting a substring in Ruby by x number of chars通过 x 个字符在 Ruby 中获取子字符串
【发布时间】:2010-12-24 19:42:37
【问题描述】:

我正在尝试生成一些 Ruby 代码,该代码将接受一个字符串并返回一个新字符串,并从其末尾删除 x 个字符 - 这些可以是实际的字母、数字、空格等。

例如:给定以下字符串

a_string = "a1wer4zx"

我需要一种简单的方法来获取相同的字符串,减去 - 比如说 - 最后三个字符。在上述情况下,这将是“a1wer”。我现在这样做的方式似乎很复杂:

an_array = a_string.split(//,(a_string.length-2))
an_array.pop
new_string = an_array.join

有什么想法吗?

【问题讨论】:

  • 它很复杂,而且,你有那种感觉很好。 Ruby 整体上是一门优雅的语言,所以当你觉得你必须跳过箍做某事时,这是一个警告,你可能会以错误的方式去做。当然,有时解决方案是不优雅的,因为那是编程的本质。不过,好的 Ruby 确实像禅宗,所以顺其自然。 :-)

标签: ruby


【解决方案1】:

这个怎么样?

s[0, s.length - 3]

或者这个

s[0..-4]

编辑

s = "abcdefghi"
puts s[0, s.length - 3]  # => abcdef
puts s[0..-4]            # => abcdef

【讨论】:

  • 有人能解释一下 s[0..-4] 是做什么的吗?
  • 我不是专家,但它肯定会看起来像环绕字符串。所以这样做s[0..-1] 将返回absdefgh。通常..用来表示一个范围
【解决方案2】:

使用这样的东西:

s = "abcdef"
new_s = s[0..-2] # new_s = "abcde"

在此处查看slice 方法:http://ruby-doc.org/core/classes/String.html

【讨论】:

    【解决方案3】:

    另一种选择是使用slice 方法

    a_string = "a1wer4zx"
    a_string.slice(0..5) 
    => "a1wer4"   
    

    文档:http://ruby-doc.org/core-2.5.0/String.html#method-i-slice

    【讨论】:

      【解决方案4】:

      另一种选择是获取字符串的chars 列表,takeing x chars 和 joining 返回字符串:

      [13] pry(main)> 'abcdef'.chars.take(2).join
      => "ab"
      [14] pry(main)> 'abcdef'.chars.take(20).join
      => "abcdef"
      

      【讨论】:

        【解决方案5】:

        如果你在 Rails 中需要它,你可以使用 first (source code)

        s = '1234567890'
        x = 4
        s.first(s.length - x) # => "123456"
        

        还有last(source code)

        s.last(2) # => "90"
        

        或者检查from/to

        【讨论】:

          猜你喜欢
          • 2021-05-17
          • 1970-01-01
          • 1970-01-01
          • 2017-11-15
          • 1970-01-01
          • 2017-08-28
          • 1970-01-01
          • 1970-01-01
          • 2012-07-18
          相关资源
          最近更新 更多