在Ruby中的第一个=符号之后获取子字符串 [英] Get substring after the first = symbol in Ruby
问题描述
纯粹出于好奇,是否有更优雅的方法来简单地获取字符串中第一个 =
符号之后的子字符串?以下工作返回name=bob
:
Purely out of curiosity, is there a more elegant way to simply get the substring after the first =
symbol in a string? The following works to give back name=bob
:
string = "option=name=bob"
string[string.index('=')+1..-1]
只是感觉不太像红宝石.这也有效:
It just doesn't feel very Ruby. This also works:
string.split('=', 2)[1]
同样,不是很优雅,尤其是因为 split
做了额外的不必要的工作.正则表达式是答案吗?我觉得这对于在字符串中查找单个字符位置的简单性来说有点矫枉过正:
Again, not very elegant especially since split
is doing extra unnecessary work. Are regular expressions the answer? I felt this was a little overkill for the simplicity of finding a single character position in a string:
string.match('=(.*)')[1]
我不得不想象这是一种极其常见的情况,不是有一个 string.after('=')
类型的方法吗?考虑到这种操作在网络上的使用频率,Ruby on Rails 是否提供类似的功能?
I have to imagine this is an extremely common situation, isn't there a string.after('=')
type method? Does Ruby on Rails provide something like this given the frequency this kind of operation is used over the web?
UPDATE:忘了说找不到符号的情况,应该返回nil
或空字符串.但是正则表达式机制和 .index
方法需要额外检查(所以不太优雅).
UPDATE: Forgot to mention the situation when the symbol is not found, nil
or empty string should be returned. But the regular expression mechanism and .index
method require an extra check for that (so less elegant).
推荐答案
不完全是 .after
,但非常接近:
Not exactly .after
, but quite close to:
string.partition('=').last
http://www.ruby-doc.org/core-1.9.3/String.html#method-i-partition
这篇关于在Ruby中的第一个=符号之后获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!