Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - Get substring after the first = symbol in Ruby

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]

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]

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: 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Not exactly .after, but quite close to:

string.partition('=').last

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-partition


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...