[英]Why do I get two lines of output from this code?
why does the following ruby program prints the output for two times? 为什么下面的ruby程序两次打印输出?
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?
为什么下面的ruby程序两次打印输出?
This is the first print 这是第一张印刷品
p @c
Result of this will become return value of method print
, which will then be printed in turn 其结果将成为方法
print
返回值,然后依次打印
p b.print
Method p
returns the value printed. 方法
p
返回打印的值。 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; 在ruby中,
p
都打印其参数并返回它,因此b.print
都打印并返回2; then p b.print
prints 2 again. 然后
p b.print
再次打印2。
The command "p" on Ruby means you wants to "print" something...Your code does the "p" command twice. Ruby上的命令“ p”表示您要“打印”某些东西……您的代码两次执行“ p”命令。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.