在Ruby中,如果为变量分配函数,为什么会自动运行?

dev*_*098 5 ruby methods irb

使用以下代码:

variable = puts "hello world".upcase
Run Code Online (Sandbox Code Playgroud)

为什么Ruby会自动将Hello world置于upcase中,而不首先调用变量?我知道你正在将函数设置为变量,如果调用该变量,它将返回返回值(在本例中为nil),但为什么Ruby puts "hello world".upcase几乎在没有权限的情况下运行该方法(没有调用它,仅仅分配给一个变量)?

Urs*_*sus 5

您没有为变量分配函数.

这是一样的

variable = (puts("hello world".upcase))
Run Code Online (Sandbox Code Playgroud)

它需要执行puts以将返回的值赋给变量变量(lol).

这是一种为变量分配方法的方法.

puts_method = method(:puts)
Run Code Online (Sandbox Code Playgroud)

  • 在ruby中有这些"可调用对象".类似于`puts_hello_word = lambda {puts"hello world"}` (2认同)
  • 并用“puts_hello_word.call”调用它 (2认同)