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

后端 未结 12 1740
盖世英雄少女心
盖世英雄少女心 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:08

    Trying to do the same thing consistently with arrays and hashes might just be a code smell, but, at the risk of my being branded as a codorous half-monkey-patcher, if you're looking for consistent behaviour, would this do the trick?:

    class Hash
        def each_pairwise
            self.each { | x, y |
                yield [x, y]
            }
        end
    end
    
    class Array
        def each_pairwise
            self.each_with_index { | x, y |
                yield [y, x]
            }
        end
    end
    
    ["a","b","c"].each_pairwise { |x,y|
        puts "#{x} => #{y}"
    }
    
    {"a" => "Aardvark","b" => "Bogle","c" => "Catastrophe"}.each_pairwise { |x,y|
        puts "#{x} => #{y}"
    }
    

提交回复
热议问题