ricks
ricks

Reputation: 3324

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}]

Upvotes: 2

Views: 4046

Answers (2)

max
max

Reputation: 102423

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.

Upvotes: 5

user5085788
user5085788

Reputation:

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

Upvotes: 1

Related Questions