在 Ruby 中如何确定一个字符串是否以另一个字符串开头?
在Ruby(没有rails)中查找一个字符串是否以另一个字符串开头的最佳方法是什么?
What the best way to find if a string starts with another in Ruby (without rails)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
[编辑] 这是我在这个问题之前不知道的事情:
start_with?
采用多个参数。[edit] This is something I didn't know before this question:
start_with?
takes multiple arguments.由于这里介绍了多种方法,我想找出哪一种最快。使用 Ruby 1.9.3p362:
所以看起来
start_with?
是其中最快的。使用 Ruby 2.2.2p95 和更新的机器更新了结果:
Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:
So it looks like
start_with?
ist the fastest of the bunch.Updated results with Ruby 2.2.2p95 and a newer machine:
steenslag 提到的方法很简洁,考虑到问题的范围,它应该被认为是正确的答案。然而,还值得知道的是,这可以通过正则表达式来实现,如果您还不熟悉 Ruby,那么这是一项需要学习的重要技能。
尝试一下 Rubular: http://rubular.com/
但在这种情况下,以下 ruby 语句将返回 true如果左侧的字符串以“abc”开头。右侧正则表达式中的 \A 表示“字符串的开头”。尝试一下 rubular——你就会清楚事情是如何运作的。
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
我喜欢
I like