什么Ruby语言构造在Rails中“respond_to do | x | .. end”?

时间:2012-07-26 06:28:16

标签: ruby-on-rails ruby syntax

我是ruby和rails的新手。有人可以指出下面的构造是什么。我在方法(def)中看到了respond_to构造。那么它是一个方法内部的方法吗?我的意思是我试图理解这里的语言结构。

我确实理解它的功能,即以给定格式发送响应。

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end

3 个答案:

答案 0 :(得分:3)

语言结构是一个红宝石块。但是如果你真的想要理解respond_to这里有一篇提供了很好概述的博客文章

How does respond_to work?

  

要理解的关键是respond_to是附加到的方法   你的控制器超类:ActionController,我们正在传入   作为一个称为块的参数:

     

...

     

在respond_to方法中,我们最终得到了一个需要一个的Proc   论点。这个参数调用了.xml和.html方法。   当我们从中调用它时,我们将什么作为参数传递给Proc   里面的respond_to?我们传入Responder类的实例。

     

所以我们最终在响应者的一个实例上调用.html和.xml   类被传递到块中(已被转换为Proc)   在respond_to方法内... Phew。

答案 1 :(得分:2)

关闭了。这就像在其他语言中使用函数一样,i。即在Ruby中,您有两个迭代集合的选项:

for elem in collection
  # do something
end

collection.each do |elem|
  # do something
end

这两者有所不同,但我没有在此描述。所以你可以看到它就像将函数传递给方法并在里面运行它。但是使用do |variables| ... end块或{ |variables| ... }块也有两种传递块的方法。如果你想编写自己接受块的方法,那么有多种方法可以做到(它们有点不同但会以相同的方式运行):

def run_3_times
  yield
  yield
  yield
end

def run_3_times(&block)
  block.call
  block.call
  block.call
end

他们两个被称为相同的方式:

run_3_times { puts 'hello' }
# will yield
hello
hello
hello

但是当没有传递阻止时会导致另一个错误:

# when using yield
LocalJumpError: no block given (yield)

# when using Proc.call
NoMethodError: undefined method `call' for nil:NilClass
from (pry):8:in `run_3_times'

这里有一些关于它的文章:

答案 2 :(得分:-1)

Ruby .respond_to?是一种测试方法。其中一件事就是采用一个符号,如果对象可以接收方法,则返回 true ;如果没有,则返回 false
  例如,:      [1,2,3] .respond_to?(:push) 将返回 true ,因为您可以在数组对象上调用 .push 。  然而
     [1,2,3] .respond_to?(:to_sym) 将返回 false ,因为您无法将数组转换为符号

链接:
 a] Ruby面向调用答案的方法,而不是对象的类型。 respond_to?