开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜