Ruby中的那些pipe道符号是什么?
Ruby中的pipe道符号是什么?
我正在学习来自PHP和Java背景的Ruby和RoR,但我仍然遇到类似这样的代码:
def new @post = Post.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @post } end end  什么是|format| 部分在做?  PHP / Java中这些pipe道符号的等效语法是什么? 
他们是产生到块的variables。
 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”。
起初我也很奇怪,但我希望这个解释/ walkthru能帮助你。
文档以相当好的方式涉及到这个问题 – 如果我的回答没有帮助,我相信他们的指导将会。
 首先,通过在shell中inputirb并按Enter键来irb Interactive Ruby解释器。 
input类似于:
 the_numbers = ['ett','tva','tre','fyra','fem'] # congratulations! You now know how to count to five in Swedish. 
只是为了让我们有一个阵容来玩。 然后我们创build循环:
 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| 可以是任何东西,只要你一直使用它。 而且要明白,这是我们正在谈论的循环,这是我以后才能得到的。 
 从do到end的代码定义了一个Ruby块 。  word format是块的参数。 该块与方法调用一起传递,被调用的方法可以为该块生成值。 
有关详细信息,请参阅Ruby上的任何文本,这是您将一直看到的Ruby的核心function。
 @names.each do |name| puts "Hello #{name}!" end 
在http://www.ruby-lang.org/en/documentation/quickstart/4/附有这样的解释:;
each方法都接受一个代码块,然后为列表中的每个元素运行该代码块,do和end之间的位就是这样一个块。 块就像一个匿名函数或lambda。 pipe道字符之间的variables是该块的参数。这里发生的是,对于列表中的每个条目,
name都绑定到该列表元素,然后expression式puts "Hello #{name}!"以该名称运行。
在Java中相当于类似的东西
 // 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(); } }); 
 块之间的参数坐在|之间 符号。 
为了使它更清晰,如果需要:
pipe道杆实质上是一个新的variables来保存先前从方法调用产生的值。 类似于:
你方法的原始定义:
 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 
其中,newVariable = 200 + 100 = 300:D!