may have already asked, but I could not find it .. here are 2 common situations (for me, when I programmed the rails ..) that upset me to write in ruby:
"a string".match(/abc(.+)abc/)[1]
in this case, I get an error because the string does not match, so the [] operator is called in nil. What I would like to find is a nicer alternative to the following:
temp="a string".match(/abc(.+)abc/); temp.nil? ? nil : temp[1]
in short, if it did not match just return nil without error
The second situation is as follows:
var = something.very.long.and.tedious.to.write
var = something.other if var.nil?
In this case, I want to assign something to var only if it is not nil, in case it is nil, I will assign something.other ..
Any suggestion? Thank!
source
share