Vivak kumar Vivak kumar - 24 days ago 5
Ruby Question

Why do I get two lines of output from this code?

why does the following ruby program prints the output for two times?

a = Proc.new do
class A
def initialize d
@c = d
end

def print
p @c
end
end

b = A.new(2)
p b.print
end

a.call


Real output

2
2


Expected output

2

Answer

why does the following ruby program prints the output for two times?

This is the first print

p @c

Result of this will become return value of method print, which will then be printed in turn

p b.print

Method p returns the value printed. That's how you get two lines with the same output.