Explain Iterator Syntax on Ruby on Rails

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

    I think you could call it iterator, because often, the block function is called more than once. As in:

    5.times do |i|
      puts "#{i} "
    end
    

    "Behind the scenes", the following steps are made:

    • The method times of the object instance 5 is called, passing the code puts "#{i} " in a Proc object instance.
    • Inside the times method, this code is called inside a loop, passing the current index as a parameter. That's what times could look like (it's in C, actually):

    class Fixnum
      def times_2(&block) # Specifying &block as a parameter is optional
        return self unless block_given?
        i = 0
        while(i < self) do
          yield i # Here the proc instance "block" is called
          i += 1
        end
        return self
      end
    end

    Note that the scope (i.e. local variables etc.) is copied into the block function:

    x = ' '
    5.times do { |i| puts "#{i}" + x }
    

提交回复
热议问题