0

I have an array of rooms: rooms_array = [room1...roomn] and each room is a hash with respective details. Each room hash has an offers hash. room1 = {...., offers=> {...},...} Now I have another array of offers hashes. avg_array = [[{offer1},{offer2}],[{offer4},{offer3}],....] Length of both the hashes is same, so first array of avg_array is for room1, second for room2 and so on... My problem is how do I add each array of avg_array into corresponding offers hash of rooms_array.

My attempt:

_rooms.values.map do |room|
  if room[:offers].count > 1
    i=0
    room[:offers] = rooms_hash[i]
    i = i + 1
  end
end
1
  • {offer1} is not a valid Ruby object. Commented Jun 15, 2017 at 23:11

1 Answer 1

3

Looks like you might be able to do something using Array.zip

rooms.zip(avg_array).map do |room,avg|
  room[:offers] = avg
  room
end

If you want to append to an existing array:

rooms.zip(avg_array).map do |room,avg|
  room[:offers] ||= []
  room[:offers].concat avg
  room
end

see: What's the 'Ruby way' to iterate over two arrays at once

Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to first check for id in both and then insert. Lets say both has an id for this purpose.
Yeah - within that loop you can examine both the room and avg object and do whatever with them. The zip means they will always be in step though, so you'll only see room[5] with avg[5]... you can't directly access avg[x+1] or avg[x-1] (you don't know what x is!) Does that make sense?
Yeah it does. I used a select statement to check for the item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.