2

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}]
1
  • 1
    Your code works fine, aren't you printing rule instead of rules by mistake? Also, each element in your array will be a string representing a JSON ["{\"event_name\":\"video_completed\",\"object_id\":1234}"] Commented Nov 16, 2018 at 14:52

2 Answers 2

5

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.

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

3 Comments

What do you mean by 'side effects of the loop'?
For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.
Thanks! I might need to go through my project and see where else i can use map instead of each haha
1

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

Comments

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.