43

只是想知道是否有一个 Ruby 习惯用法用于从索引中提取子字符串直到字符串结尾。我知道str[index..-1]通过将一个范围对象传递给String'[]方法可以工作,但它有点笨拙。例如,在 python 中,您可以编写str[index:]which 会隐式地为您获取字符串的其余部分。

例子:

s = "hello world"
s[6..-1] # <-- "world"

有什么比 更好的s[6..-1]吗?

4

6 回答 6

8

Ruby 2.6 引入了无限范围,这基本上消除了必须指定结束索引的需要。在您的情况下,您可以执行以下操作:

s = "hello world"
s[6..]
于 2019-06-28T15:03:37.140 回答
7

我认为不是。

似乎这Range是更好的方法。

于 2013-02-13T06:37:20.060 回答
7

如果你愿意,这里是“更好的”。您可以扩展 ruby​​ String 类,然后在您的代码中使用此方法。例如:

class String
  def last num
    self[-num..-1]
  end
end

进而:

s = "hello world"
p s.last(6)
于 2013-02-13T06:55:34.803 回答
5

要从范围中获取字符串:

s = 'hello world'
s[5..s.length - 1] # world

但是,如果您只想获得最后一句话:

'hello world'.split(' ').last # world
于 2016-09-16T15:05:33.543 回答
2

您可以扩展String类。不确定它是否是红宝石成语:

class String
  def last(n)
    self[(self.length - n)..-1]
  end
end
于 2013-02-13T06:55:52.670 回答
1

Rails 的activesupport库(可以作为独立于 Rails 的 gem 安装)from为字符串添加了一个方法:

> s = "hello world"
"hello world"
> s.from(6)
"world"

https://api.rubyonrails.org/classes/String.html#method-i-from

于 2018-09-28T21:21:34.637 回答