简体   繁体   English

为什么从此代码中获得两行输出?

[英]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.

相关问题 更改两行的顺序后,为什么我得到零? - Why do I get a nil after changing the order of two lines? 如何在Ruby中仅从字符串(EC2盒的控制台输出)中获取新行? - How do I get only the new lines from a string (an EC2 box' console output) in Ruby? 为什么我不需要额外的代码行? Ruby 代码学院 - Why do I not need the extra lines of code? Ruby Codeacademy 使用Nokogiri“搜索”时为什么会输出错误? - Why do I get bad output when using Nokogiri “search”? 为什么从我的Ruby代码中收到此“语法错误,意外的tIDENTIFIER”错误消息? - Why do I get this “syntax error, unexpected tIDENTIFIER” error message from my Ruby code? 为什么由于两个反斜杠\\\\而导致错误? - Why do I get an error due to two backslashes \\? 为什么我的代码中会出现“未定义的局部变量或方法”? - Why do I get “undefined local variable or method” in my code? 如何从grep的输出中选择 - How do I get a selection from the output of a grep 为什么在以下代码中没有收到输出? - why I received no output in the following code? 为什么我得到相同的输出DateTime.now.in_time_zone(-4)和DateTime.now.in_time_zone(-3) - Why do I get the same output for DateTime.now.in_time_zone(-4) and DateTime.now.in_time_zone(-3)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM