'How can i create JSON array of JSON objects in ruby from a loop

I am trying to loop through some video objects and i am trying to build a JSON array that looks like this:

[{"event_name":"video_completed","object_id":123456789}]

I created a method to do this:

def self.getEngagementRules(videos)

    rules = []

    videos.each do |video|

        rule = {
            event_name: "video_completed",
            object_id: video.image_hash.to_i
        }

        rules << rule.to_json
    end

    rules
end

I am creating hashes and then turning them into JSON and appending it to my array rules but when i run:

puts rules

i get {"event_name":"video_completed","object_id":123456789}

instead of [{"event_name":"video_completed","object_id":123456789}]

What is the correct way of doing this so i can loop through multiple videos and get my desired result.

It should be able to handle multiple videos and output:

[{"event_name":"video_completed","object_id":123456789}, {"event_name":"video_completed","object_id":123456789}]


Solution 1:[1]

You want to first compose a ruby array and then convert it to JSON:

rules = videos.map do |video|
  {
    event_name: "video_completed",
    object_id: video.image_hash.to_i
   }
end
rules.to_json

.each should only be used when you are only concerned with the side effects of the loop and not the return value.

Otherwise you should be using .map, .inject, .each_with_object etc which signify to other programmers that you care about the return value.

Solution 2:[2]

Your code works right, you have an array but puts prints each element of the array in a separate line

puts [1, 2, 3]

1
2
3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 luisenrike