Explain Iterator Syntax on Ruby on Rails

前端 未结 7 1259
慢半拍i
慢半拍i 2021-01-20 03:25

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

7条回答
  •  遇见更好的自我
    2021-01-20 04:09

    Methods can take a construct called "Blocks". These are anonymous methods that get passed into the method.

    Another syntax for this is:

    method_call { |var| do_something(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.

    Does this help?

    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.

    In other words, they are using the pattern to create a DSL of sorts that lets you configure what you respond to.

提交回复
热议问题