调用/应用lambda与函数调用-Ruby中的语法不同.为什么?

问题描述:

我是Ruby的新手,仍然尝试理解一些语言设计原则.如果我做对了,Ruby中的lambda表达式调用必须使用方括号,而"regular"函数调用必须使用"regular"/圆括号.

I am kinda new to Ruby and still trying to understand some of the language design principles. IF I've got it right, the lambda expression call in Ruby must be with square braces, while the "regular" function call is with "regular"/round braces.

语法是否有特殊原因?或者换句话说,(为什么)调用者应该知道他们是调用函数还是应用lambda表达式?

Is there a special reason that the syntax is different? Or, in other words, (why) should the caller be aware whether they call a function or apply a lambda expression?

在Ruby中,方法不是lambda(例如,在JavaScript中).

Because in Ruby, methods are not lambdas (like, for example, in JavaScript).

方法始终属于对象,可以被继承(通过子类或混合),可以在对象的本征类中被覆盖,并且可以被赋予一个块(即lambda).它们具有自己的变量范围.方法定义示例:

Methods always belong to objects, can be inherited (by sub-classing or mixins), can be overwritten in an object's eigenclass and can be given a block (which is a lambda). They have their own scope for variables. Example method definition:

a = :some_variable
def some_method
  # do something, but not possible to access local variable a
end

# call with:
some_method

但是lambdas/procs是普通的闭包,可能存储在变量中-没有别的:

However lambdas/procs are plain closures, maybe stored in a variable - nothing else:

a = :some_variable
some_lambda = lambda{
  # do something, access local variable a if you want to
}

# call with:
some_lambda[]

Ruby将两种方法与强大的语法结合在一起,例如,传递块:

Ruby combines both approaches with a powerful syntax, for example, passing blocks:

def some_method_with_block(a)
  # do something, call given block (which is a lambda) with:
  yield(a) ? 42 : 21
end

# example call:
some_method_with_block(1) do |x|
  x.odd?
end #=> 42