Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...