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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…