ruby syntactic sugar: dealing with nils..
Posted
by
luca
on Stack Overflow
See other posts from Stack Overflow
or by luca
Published on 2010-12-30T19:15:43Z
Indexed on
2010/12/30
19:53 UTC
Read the original article
Hit count: 395
ruby-on-rails
|ruby
probably asked already but I couldn't find it.. here are 2 common situation (for me while programming rails..) that are frustrating to write in ruby:
"a string".match(/abc(.+)abc/)[1]
in this case I get an error because the string doesn't match, therefore the [] operator is called upon nil. What I'd like to find is a nicer alternative to the following:
temp="a string".match(/abc(.+)abc/); temp.nil? ? nil : temp[1]
in brief, if it didn't match simply return nil without the error
The second situation is this one:
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's not nil, in case it's nil I'll assign something.other..
Any suggestion? Thanks!
© Stack Overflow or respective owner