How to pass parameters do a call to Logger.info?
I have a method like:
def test(p1, p2)
logger.info 'calling test with p1=' + p1 + ' p2 = 开发者_JAVA百科' + p2
end
Getting a cast error, how should I be doing this neatly?
Your cast error is probably because p1 or p2 is not a string type. Ruby's string interpolation will handle this for you:
def test(p1, p2)
logger.info "calling test with p1=#{p1} p2=#{p2}"
end
Here's how it works: ruby calls to_s
on any variables in the string (denoted by #{}
) which converts them to a string. Every object in ruby has this method, so you don't need to worry about it from there. I hope this helps!
UPDATE: This was a simple, but interesting question because there's more to it than meets the eye (like transformers). The way Ruby does this actually opens the door to functionality you can use in your own classes. I turned the answer into a blog post with code samples and a more detailed explanation:
Ruby String Interpolation
精彩评论