简体   繁体   中英

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

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.

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

    def print
     p @c
    end
  end

  b = A.new(2)
  b.print #you need just to call method print
end

a.call

In ruby, p both prints its argument and returns it, so b.print both prints and returns 2; then p b.print prints 2 again.

The command "p" on Ruby means you wants to "print" something...Your code does the "p" command twice. Just remove the unwanted and it will work.

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

    def print
     p @c #FIRST PRINT
    end
  end

  b = A.new(2)
  p b.print #SECOND PRINT
end

a.call

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM