This is a bit of a n00b question. I'm trying to figure out how I can refactor a nested each loop like the one below so that I am not declaring extra variables that I won't need later and so that my code runs quicker.

some_array = [["one", 2, 3], ["two", 3, 4], ["three", 4, 5]]
output = {}

some_array.each do |a|
  current_group = []

  another_array.each do |b|
    current_group << b if something == true
  end

  output[a[0]] = current_group
end

The output is returned as a hash of arrays. some_array is a nested array where the first element in each sub-array is a string and another_array is an array of hashes.

share|edit|flag
   upvote
  flag
What is group? –  Mark Reed 18 mins ago
1 upvote
  flag
You probably want .inject –  Jon 17 mins ago
   upvote
  flag
How come your outer loop is not using a? –  ruakh 15 mins ago
   upvote
  flag
I just edited the code. group is a. –  ACIDSTEALTH 13 mins ago
   upvote
  flag
what is something? –  Amit Joki 11 mins ago

1 Answer 1

I can't tell exactly what you're doing from that code - what is group? How does the condition tie some_array and other_array together? But in general, if you want to build a new array or hash, the idiom to reach for is something with inject (a.k.a. reduce). The pattern is this:

output = some_array.inject({}) do |partial_output, item|
   ...
   new value of partial_output after this loop iteration
end
share|edit|flag

Your Answer

 

Not the answer you're looking for? Browse other questions tagged or ask your own question.