在Ruby on Rails上解释Iterator语法 [英] Explain Iterator Syntax on Ruby on Rails
问题描述
我开始学习Ruby on Rails并发现自己对语法感到困惑,所以我不得不阅读一些Ruby语法。我从 http:/中学习了语法/www.cs.auckland.ac.nz/references/ruby/doc_bundle/Manual/man-1.4/syntax.html :
I started learning Ruby on Rails and found myself confounded by the syntax, so I had to read about somet of the Ruby syntax. I learned the syntax from http://www.cs.auckland.ac.nz/references/ruby/doc_bundle/Manual/man-1.4/syntax.html:
method_call do [`|' expr...`|'] expr...end
他们称之为迭代者。我理解一个迭代器运行循环,但我不明白我应该如何阅读这个或者在这个语法中发生了什么。我一直在RoR的截屏视频中看到它并且这些词语有意义,但我实际上不知道发生了什么。有人可以向我解释一下吗?
They call it an Iterator. I understand an iterator runs through a loop, but I don't understand how exactly I'm supposed to read this or what's going on in in this syntax. I see it all the time in RoR screencasts and the words make sense, but I actually have no idea what's going on. Could anyone explain this to me?
编辑:示例
respond_to do |format|
format.json
format.xml { render :xml => @posts }
end
推荐答案
方法可以采取一个名为Blocks的结构。这些是传递给方法的匿名方法。
Methods can take a construct called "Blocks". These are anonymous methods that get passed into the method.
另一种语法是:
method_call { |var| do_something(var) }
基本上,你是说对于迭代中的每个项目,将其命名为 var并对该项目执行某些操作。该方法只是调用您传入的块,因为它会生成项目。
Basically, you are saying that for each item in an iteration, name it "var" and do something with that item. The method simply calls your block that you passed in as it "yields" items to it.
这有用吗?
编辑:在您的示例中,您以有趣的方式使用迭代器模式...可能只将一个格式
对象传递到你的块,所以你可以告诉它要处理哪些格式,以及当你看到它时该怎么做。
edit: In your example, you they are using the iterator pattern in a funny way... probably only passing one format
object into your block, so you can then tell it which formats to handle, and what to do when you see it.
换句话说,他们正在使用该模式创建各种DSL,以便您配置响应的内容。
In other words, they are using the pattern to create a DSL of sorts that lets you configure what you respond to.
这篇关于在Ruby on Rails上解释Iterator语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!