English 中文(简体)
• 优化多阵列的循环?
原标题:Best way to iterate over multiple arrays?

What s is the best (beauty and efficient in terms of performance) way to iterate over multiple arrays in Ruby? Let s say we have an arrays:

a=[x,y,z]
b=[ a , b , c ]

我希望:

x a
y b
z c

感谢。

最佳回答

<代码>zip 阵列物体的方法:

a.zip b do |items|
    puts items[0], items[1]
end
问题回答

另一种办法是使用<代码>each_with_index。 快速基准显示,这一比率略高于使用zi。

a.each_with_index do |item, index|
  puts item, b[index]
end

基准:

a = ["x","y","z"]
b = ["a","b","c"]

Benchmark.bm do |bm|
  bm.report("ewi") do
    10_000_000.times do
      a.each_with_index do |item, index|
        item_a = item
        item_b = b[index]
      end
    end
  end
  bm.report("zip") do
    10_000_000.times do
      a.zip(b) do |items|
        item_a = items[0]
        item_b = items[1]
      end
    end
  end
end

成果:

      user     system      total        real
ewi  7.890000   0.000000   7.890000 (  7.887574)
zip 10.920000   0.010000  10.930000 ( 10.918568)
>> a=["x","y","z"]
=> ["x", "y", "z"]
>> b=["a","b","c"]
=> ["a", "b", "c"]
>> a.zip(b)
=> [["x", "a"], ["y", "b"], ["z", "c"]]
>>

我愿在利用鲁比拉多阵列进行循环使用。 希望这一帮助。

bigarray = []
bigarray << array_1
bigarray << array_2
bigarray << array_3
variableName = bigarray.transpose

variableName.each do |item1,item2,item3|

# do stuff per item
# eg 
puts "item1"
puts "item2"
puts "item3"

end




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签