Explain Iterator Syntax on Ruby on Rails

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

    In the case of iterators, think of them like an interface in Java: you can do a for-loop in Ruby, but all the objects that you might want to iterate over (should) implement the 'each' method which takes a block (i.e. a closure, an anonymous function).

    Blocks are used all over the place in Ruby. Imagine you have this array:

    [1, 2, 3, 4, 5, 6].each do |i| puts i.to_s end
    

    Here, you are creating the array and then you are calling the 'each' method on it. You pass the block to it. You could separate this out, like this:

    arr = [1, 2, 3, 4, 5, 6]
    string_printer = lambda do |i| puts i.to_s end
    arr.each(&string_printer)
    

    This kind of interface is implemented in other things: the Hash collection lets you iterate over the key-value pairs:

    {:name => "Tom", :gender => :male}.each do |key, value| puts key end
    

    The do..end can be replaced with braces, like this:

    [1, 2, 3, 4, 5, 6].each {|i| puts i.to_s }
    

    This kind of iteration is made possible because of the functional-programming that Ruby employs: if you are creating a class that needs to iterate over something, you can also implement the each method. Consider:

    class AddressBook
      attr_accessor :addresses
      def each(&block)
        @addresses.each {|i| yield i }
      end
    end
    

    All sorts of classes implement interesting functionality through this block pattern: look at String's each_line and each_byte method, for instance.

提交回复
热议问题