使用以下代码:
variable = puts "hello world".upcase
Run Code Online (Sandbox Code Playgroud)
为什么Ruby会自动将Hello world置于upcase中,而不首先调用变量?我知道你正在将函数设置为变量,如果调用该变量,它将返回返回值(在本例中为nil),但为什么Ruby puts "hello world".upcase几乎在没有权限的情况下运行该方法(没有调用它,仅仅分配给一个变量)?
您没有为变量分配函数.
这是一样的
variable = (puts("hello world".upcase))
Run Code Online (Sandbox Code Playgroud)
它需要执行puts以将返回的值赋给变量变量(lol).
这是一种为变量分配方法的方法.
puts_method = method(:puts)
Run Code Online (Sandbox Code Playgroud)