这是真的,你不知道need匿名函数(或者 lambda,或者任何你想称呼的名称)。但有很多事情你不知道need。您不需要类,只需将所有实例变量传递给普通函数即可。然后
class Foo
attr_accessor :bar, :baz
def frob(x)
bar = baz*x
end
end
会成为
def new_Foo(bar,baz)
[bar,baz]
end
def bar(foo)
foo[0]
end
# Other attribute accessors stripped for brevity's sake
def frob(foo,x)
foo[0] = foo[1]*x
end
Similarly, you don't need any loops except for loop...end
with if
and break
. I could go on and on.1 But you want to program with classes in Ruby. You want to be able to use while
loops, or maybe even array.each { |x| ... }
, and you want to be able to use unless
instead of if not
.
就像这些功能一样,匿名函数可以帮助您优雅、简洁、明智地表达事物。能够写作some_function(lambda { |x,y| x + f(y) })
比必须写好得多
def temp(x,y)
x + f(y)
end
some_function temp
必须中断代码流才能写出一个代码,这要麻烦得多def
fed 函数,然后必须给它一个无用的名称,这样才能清楚地编写内联操作。确实没有你的地方must使用 lambda,但有很多地方我很想rather使用 lambda。
Ruby 通过块解决了许多 lambda 使用案例:所有函数,例如each
, map
, and open
可以将块作为参数的基本上是采用特殊情况的匿名函数。array.map { |x| f(x) + g(x) }
是相同的array.map(&lambda { |x| f(x) + g(x) })
(其中&
只是让 lambda 变得“特殊”,就像裸块一样)。再说一遍,你could单独写一个def
每次都执行联邦功能 - 但为什么你要want to?
Languages other than Ruby which support that style of programming don't have blocks, but often support a lighter-weight lambda syntax, such as Haskell's \x -> f x + g x
, or C#'s x => f(x) + g(x);
2. Any time I have a function which needs to take some abstract behavior, such as map
, or each
, or on_clicked
, I'm going to be thankful for the ability to pass in a lambda instead of a named function, because it's just that much easier. Eventually, you stop thinking of them as somehow special—they're about as exciting as literal syntax for arrays instead of empty().append(1).append(2).append(3)
. Just another useful part of the language.
1:在退化的情况下,你真的只需要八个指令 http://en.wikipedia.org/wiki/Brainfuck: +-<>[].,
. <>
沿着数组移动一个假想的“指针”;+-
递增和递减当前单元格中的整数;[]
执行非零循环;和.,
做输入和输出。事实上,你真的只需要一条指令 http://en.wikipedia.org/wiki/One_instruction_set_computer, 例如subleq a b c
(减去a
from b
并跳转到c
如果结果小于或等于零)。
2:我从未真正使用过 C#,因此如果该语法错误,请随时更正。