纯粹出于好奇,有没有更优雅的方法可以简单地将子字符串放在字符串中第一个=
符号之后?以下是回馈name=bob
的工作:
string = "option=name=bob"
string[string.index('=')+1..-1]
只是感觉不太像Ruby .这也适用于:
string.split('=', 2)[1]
再说一次,不是很优雅,尤其是因为split
是做额外的不必要的工作.正则表达式就是答案吗?我觉得这有点过分了,因为在字符串中查找单个字符的位置很简单:
string.match('=(.*)')[1]
我不得不想象这是一种非常常见的情况,难道没有一种string.after('=')
类型的方法吗?鉴于这种操作在web上的使用频率,Ruby on Rails是否提供了类似的功能?
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).