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

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

    If you use the enumerable mixin (as Rails does) you can do something similar to the php snippet listed. Just use the each_slice method and flatten the hash.

    require 'enumerator' 
    
    ['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
    
    # is equivalent to...
    
    {'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
    

    Less monkey-patching required.

    However, this does cause problems when you have a recursive array or a hash with array values. In ruby 1.9 this problem is solved with a parameter to the flatten method that specifies how deep to recurse.

    # Ruby 1.8
    [1,2,[1,2,3]].flatten
    => [1,2,1,2,3]
    
    # Ruby 1.9
    [1,2,[1,2,3]].flatten(0)
    => [1,2,[1,2,3]]
    

    As for the question of whether this is a code smell, I'm not sure. Usually when I have to bend over backwards to iterate over something I step back and realize I'm attacking the problem wrong.

提交回复
热议问题