从索引到字符串结尾的子字符串的 Ruby 习语

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14847760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:44:43  来源:igfitidea点击:

Ruby idiom for substring from index until end of string

rubystringsubstringsliceidiomatic

提问by Sherwin Yu

Just wondering if there's a Ruby idiom for extracting a substring from an index until the end of the string. I know of str[index..-1]which works by passing in a range object to the String's []method but it's a little clunky. In python, for example, you could write str[index:]which would implicitly get you the rest of the string.

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

Example:

例子:

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

Is there anything nicer than s[6..-1]?

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

采纳答案by Paul Brit

I think it isn't.

我认为不是。

It seems that Rangeis better way to do it.

似乎这Range是更好的方法。

回答by Yevgeniy Anfilofyev

Here is 'nicer' if you wish. You can extend ruby String class and then use this method into your code. For example:

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

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

And then:

进而:

s = "hello world"
p s.last(6)

回答by Simon Tsang

To get the string from a range:

要从范围中获取字符串:

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

However, if you just want to get the last word:

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

'hello world'.split(' ').last # world

回答by vicentazo

Ruby 2.6 introduced endless ranges, which basically remove the need to have to specify the end index. In your case, you can do:

Ruby 2.6 引入了无穷范围,这基本上消除了必须指定结束索引的需要。在你的情况下,你可以这样做:

s = "hello world"
s[6..]

回答by Flauwekeul

You can extend the Stringclass. Not sure if it's a ruby idiom though:

您可以扩展String该类。不确定它是否是 ruby​​ 习语:

class String
  def last(n)
    self[(self.length - n)..-1]
  end
end

回答by MothOnMars

Rails' activesupportlibrary (which can be installed as a gem independent of Rails) adds a frommethod to strings:

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

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

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

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