Ruby中的那些管道符号是什么?

时间:2009-03-20 10:13:29

标签: ruby syntax

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中这些管道符号的等效语法是什么?

7 个答案:

答案 0 :(得分:50)

它们是产生块的变量。

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”。

答案 1 :(得分:30)

起初这对我来说也很奇怪,但我希望这个解释/ walkthru可以帮助你。

文档touches the subject,以一种非常好的方式 - 如果我的答案没有帮助,我相信他们的指南会。

首先,在shell中键入irb并点击 Enter ,启动Interactive 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|可以是任何内容,只要您始终如一地使用它即可。并且理解它是我们正在谈论的循环,这是我直到后来才得到的东西。

答案 2 :(得分:6)

doend的代码定义了Ruby block。单词format是块的参数。该块与方法调用一起传递,被调用的方法可以yield赋值给块。

有关详细信息,请参阅Ruby上的任何文本,这是Ruby的核心功能,您将一直看到它。

答案 3 :(得分:6)

@names.each do |name|
  puts "Hello #{name}!"
end
http://www.ruby-lang.org/en/documentation/quickstart/4/处的

附有此解释:

  

each是一个接受代码块然后为列表中的每个元素运行该代码块的方法,doend之间的位就是这样一个块。块就像匿名函数或lambda。管道字符之间的变量是该块的参数。

     

这里发生的是,对于列表中的每个条目,name绑定到该列表元素,然后使用该名称运行表达式puts "Hello #{name}!"

答案 4 :(得分:3)

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();
    }
});

答案 5 :(得分:3)

块的参数位于|符号之间。

答案 6 :(得分:1)

如果需要,使其更清晰:

管道棒基本上是一个新变量来保存从方法调用先前生成的值。类似于:

您方法的原始定义:

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!

相关问题