Rohan
Rohan

Reputation: 2226

Ruby 1.9 prints strings twice

class Test
def printsomething
p "lol"
end
end
teet = Test.new
p "#{teet.printsomething}"

Output for above code is "lol"\n"lol"

why is this happening? I am running ruby 1.9.2 Archlinux x86_64

Upvotes: 1

Views: 590

Answers (2)

Mike Bethany
Mike Bethany

Reputation:

p is an inspect not really meant to be used to output text string. What it does is prints out the literal content of an object not an escaped string.

Just replace p with puts

You can see what I mean if you do this:

p "#{teet}"
=> "#<Test:0x00000100850678>"

Notice how it's inside quotes.

Upvotes: 2

adamax
adamax

Reputation: 3865

First thing that Ruby does when it sees a double-quoted string is replacing the #{expr} parts with the result of evaluated expr. For example, "#{2+2}" becomes "4". So, let's see what happens here. Ruby evaluates teet.printsomething. During this evaluation it executes the method and it prints "lol" in the 3-rd line. Note that although the method printsomething doesn't have a return statement, it nevertheless returns some value: it's the value returned by the last statement of that method. The return value of p object is the object itself, so the result of the method printsomething is "lol". This result now replaces the #{} part in the string, and the string becomes "lol" instead of "#{teet.printsomething}". Now the p method in the 7-th line is executed and outputs "lol" again.

What happens if you replace p with puts? The difference is that the return value of puts is nil. When the result of expr is nil, the whole expression #{} is replaced by empty string. So the 7-th line becomes puts "". As a result, the whole program outputs "lol" followed by an empty line.

Upvotes: 0

Related Questions