What is the “right” way to iterate through an array in Ruby?

后端 未结 12 1734
盖世英雄少女心
盖世英雄少女心 2020-12-04 04:18

PHP, for all its warts, is pretty good on this count. There\'s no difference between an array and a hash (maybe I\'m naive, but this seems obviously right to me), and to ite

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 05:02

    Using the same method for iterating through both arrays and hashes makes sense, for example to process nested hash-and-array structures often resulting from parsers, from reading JSON files etc..

    One clever way that has not yet been mentioned is how it's done in the Ruby Facets library of standard library extensions. From here:

    class Array
    
      # Iterate over index and value. The intention of this
      # method is to provide polymorphism with Hash.
      #
      def each_pair #:yield:
        each_with_index {|e, i| yield(i,e) }
      end
    
    end
    

    There is already Hash#each_pair, an alias of Hash#each. So after this patch, we also have Array#each_pair and can use it interchangeably to iterate through both Hashes and Arrays. This fixes the OP's observed insanity that Array#each_with_index has the block arguments reversed compared to Hash#each. Example usage:

    my_array = ['Hello', 'World', '!']
    my_array.each_pair { |key, value| pp "#{key}, #{value}" }
    
    # result: 
    "0, Hello"
    "1, World"
    "2, !"
    
    my_hash = { '0' => 'Hello', '1' => 'World', '2' => '!' }
    my_hash.each_pair { |key, value| pp "#{key}, #{value}" }
    
    # result: 
    "0, Hello"
    "1, World"
    "2, !"
    

提交回复
热议问题