在Ruby中使用圆括号和块时会感到困惑

Cur*_*ind 3 ruby

在Surface,Ruby看起来与其他对象orieinted语言非常相似,如Java,Php,C等.

但是,当我们开始遇到障碍时,事情变得有点奇怪.

例如,这是有效的

(0...8).max()
 => 7 
Run Code Online (Sandbox Code Playgroud)

但事实并非如此

(0...8).map(puts "hello world")
hello world
ArgumentError: wrong number of arguments(1 for 0)
Run Code Online (Sandbox Code Playgroud)

Apprantly,地图方法不带参数,但不对块,所以通过更换(){}修复错误.

(0...8).map{puts "hello world"}
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
 => [nil, nil, nil, nil, nil, nil, nil, nil] 
Run Code Online (Sandbox Code Playgroud)

然后,有一些方法应该采取 - 块和参数

8.downto(1){puts "hello world"}
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
 => 8 
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是如果我应该使用(),{}或两者都给定方法混淆.在什么基础上决定?

  • 它是基于每个方法固定的,我只记得该方法采用的方法(块或参数)?
  • 或者,如果方法采用块{}或参数,是否有任何其他逻辑推理依据它来决定()

请帮我理解

Sir*_*ius 6

方法调用后的括号实际上是可选的.

(0...8).map{puts "hello world"} 相当于 (0...8).map() {puts "hello world"}

所以你并没有真正取代它们.

块的接受完全取决于方法,它们可以在方法声明中指定:

def method(param, &block)
  block.call
end
Run Code Online (Sandbox Code Playgroud)

这将允许块作为方法内的变量被访问,并通过block.call例如调用.

它们也可以通过使用yield关键字隐式使用:

def method(param)
  yield
end
Run Code Online (Sandbox Code Playgroud)

因此,您必须参考API文档以确定接受与否.