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
感谢。
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
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 ...
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 ...
All of the following API do the same thing: open a file and call a block for each line. Is there any preference we should use one than another? File.open("file").each_line {|line| puts line} open("...
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?
Here s the string: 04046955104021109 I need it to be formatted like so: 040469551-0402-1109 What s the shortest/most efficient way to do that with ruby?
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
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 ...
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 ...