[英]Ruby: How to pass the result of an block as an argument
Can I some how pass the result of an evaluated block as an argument to a function? 我可以将评估块的结果作为参数传递给函数吗?
This illustrates what I want to do by using a helper function ( do_yield
): 这说明了我想通过使用辅助函数( do_yield
)来做什么:
#!/usr/bin/env ruby
def do_yield
yield
end
def foo a
#'a' must be an array
puts "A: [#{a.join(", ")}]"
end
foo (do_yield{
a = []
a << 1
})
Can I do this without creating my own helper function? 我可以在不创建自己的辅助函数的情况下执行此操作吗? Preferably by using facilities in the language, if the language does not offer a way to do it, then is there an existing function I can use instead of my own do_yield
最好通过使用该语言中的工具,如果该语言没有提供一种实现方法,那么是否可以使用现有功能代替我自己的do_yield
So, you want to pass a result of executing some code into some other code? 因此,您想将执行某些代码的结果传递给其他代码吗? You just need to convert your "block" to an expression (by making it a proper method, for example) 您只需要将“块”转换为表达式(例如,通过使其成为适当的方法)
def bar
a = []
a << 1
end
foo bar
If your code is really this simple (create array and append element), you can use the code grouping constructs (which combine several statements/expressions into one expression) 如果您的代码确实如此简单(创建数组和追加元素),则可以使用代码分组构造(将多个语句/表达式组合为一个表达式)
foo((a = []; a << 1))
or 要么
foo(begin
a = []
a << 1
end)
Personally, I'd definitely go with the method. 就我个人而言,我绝对会使用该方法。 Much simpler to read. 更容易阅读。
The piece of terminology you probably want to search for here is lambda
- a lambda being an anonymous function that can be passed around as a parameter. 您可能要在这里搜索的术语是lambda
- lambda是可以作为参数传递的匿名函数。
So to do what you are describing with a Lambda you might do this: 因此,要使用Lambda进行描述,您可以这样做:
my_lambda = lambda do
a = []
a << 1
end
def foo a
#'a' must be an array
puts "A: [#{a.join(", ")}]"
end
foo my_lambda.call
Of course you can have parameterised lambdas and if foo
was expecting a lambda you could have it call #{a.call.join(", ")}]
( your actual code has double-quotes everywhere so not sure it would work ) so that the evaluation only happened when it was passed. 当然,您可以参数化lambda,如果foo
期望使用lambda,则可以调用#{a.call.join(", ")}]
(您的实际代码到处都有双引号,因此不确定它是否可以工作)评估仅在通过时才进行。
This is an interesting and powerful part of Ruby so it is worth learning about. 这是Ruby有趣而强大的部分,因此值得学习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.