Explain Iterator Syntax on Ruby on Rails

前端 未结 7 1071
慢半拍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:02

    What you see there is a block of code, the syntax is a bit awkward when you first see it.

    So, basically, with iterators your have a "thing" that may be repeated, and it receives a block to know what to do.

    For instance the Range class has a method called "each" which receives the block of code to execute on each element in the range.

    Let's say you want to print it:

    range = 1..10 #range literal 
    range.each {|i|
        puts i
    }
    

    The code: {|i| puts i} is a block that says what to do when this range iterates over each one of its elements. The alternate syntax is the one you posted:

     range.each do |i|
          puts i 
     end
    

    These blocks are used with iterators, but they are not limited to "iteration" code, you can use them in other scenarios, for instance:

    class Person 
      def initialize( with_name ) 
        @name = with_name
      end
      # executes a block 
      def greet 
          yield @name #passes private attribute name to the block 
      end 
    end 
    
    p = Person.new "Oscar" 
    p.greet { |n|
         puts "Name length = #{n.length}"
         puts "Hello, #{n}"
    }
    

    Prints:

    Name length = 5
    Hello, Oscar
    

    So, instead of having a greet method with a fixed behavior, using block let the developer specify what to do, which is very helpful with iterators, but as you have just witness not the only place. In your case, that block is letting you specify what to do in the respond_to method.

提交回复
热议问题