Rails: How to log an object that might be nil?
What is the shortest code to log myvar
, knowing it can be nil
?
Hopefully something s开发者_运维知识库horter than this:
if (myvar==nil)
logger.debug "myvar is nil"
else
logger.debug "myvar is " + @myvar.to_s
end
logger.debug "myvar is: " + myvar.inspect
logger.debug "myvar is #{myvar.nil? ? 'nil' : myvar_to_s}"
Using #{...}
inside of double quotes tells Ruby to evaluate the inside of the {...}
as though it were normal Ruby code.
The myvar.nil? ? 'nil' : myvar_to_s
portion first calls the nil?
method on myvar
. If it returns true
, the string 'nil'
is used. Otherwise, the value of myvar.to_s
is used.
精彩评论