在Ruby中,竖线符号的作用是什么?
我正在学习Ruby和RoR,之前主要使用PHP和Java。但我一直看到这样的代码:
def new
@post = Post.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
在这里,|format|
是什么意思?在PHP/Java中,相当于这些管道符号的语法是什么?
它们是传递给块的变量。
def this_method_takes_a_block
yield(5)
end
this_method_takes_a_block do |num|
puts num
end
输出结果为"5"。一个更加晦涩的例子:
def this_silly_method_too(num)
yield(num + 5)
end
this_silly_method_too(3) do |wtf|
puts wtf + 1
end
输出结果为“9”。irb
并按下Enter启动交互式Ruby解释器。the_numbers = ['ett','tva','tre','fyra','fem'] # congratulations! You now know how to count to five in Swedish.
只是为了有一个可以操作的数组。然后我们创建循环:
the_numbers.each do |linustorvalds|
puts linustorvalds
end
它将输出所有数字,以换行符分隔。
在其他语言中,您需要编写类似于:
for (i = 0; i < the_numbers.length; i++) {
linustorvalds = the_numbers[i]
print linustorvalds;
}
需要注意的重要事项是,|thing_inside_the_pipes|
可以是任何东西,只要你一直使用它。另外要明白的是,我们在谈论循环,这是我在后来才明白的。
for linustorvalds in the_numbers do print linustorvalds
。可能更加直观一些。 - Steve Bennett@names.each do |name|
puts "Hello #{name}!"
end
each
方法接受一个代码块并为列表中的每个元素运行该代码块。在do
和end
之间的部分就是这样的一个代码块。一个代码块类似于一个匿名函数或lambda
。管道字符之间的变量是该代码块的参数。name
绑定到该列表元素,然后使用该名称运行表达式puts "Hello #{name}!"
。do
到end
的代码定义了一个Ruby块。单词format
是块的参数。该块随方法调用一起传递,被调用的方法可以向块中yield
值。// Prior definitions
interface RespondToHandler
{
public void doFormatting(FormatThingummy format);
}
void respondTo(RespondToHandler)
{
// ...
}
// Equivalent of your quoted code
respondTo(new RespondToHandler(){
public void doFormatting(FormatThingummy format)
{
format.html();
format.xml();
}
});
块的参数位于|
符号之间。
def example_method_a(argumentPassedIn)
yield(argumentPassedIn + 200)
end
如何使用:
example_method_a(100) do |newVariable|
puts newVariable;
end
这几乎与写下以下内容一样:
newVariable = example_method_a(100)
puts newVariable
在这里,新变量 = 200 + 100 = 300 :D!
|wtf|
块结束时,wtf
去哪里了? - ThorSummoneryield
的调用方传递的任何值。 - August Lilleaas