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



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















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]









share|improve this question

















  • 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"]

    – byrdEmmanuel
    Nov 16 '18 at 14:52

















0















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]









share|improve this question

















  • 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"]

    – byrdEmmanuel
    Nov 16 '18 at 14:52













0












0








0








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]









share|improve this question














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]






ruby-on-rails ruby






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 14:39









RickSRickS

752716




752716







  • 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"]

    – byrdEmmanuel
    Nov 16 '18 at 14:52












  • 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"]

    – byrdEmmanuel
    Nov 16 '18 at 14:52







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

– byrdEmmanuel
Nov 16 '18 at 14:52





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

– byrdEmmanuel
Nov 16 '18 at 14:52












2 Answers
2






active

oldest

votes


















2














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 (and know what you are doing).






share|improve this answer























  • What do you mean by 'side effects of the loop'?

    – RickS
    Nov 16 '18 at 14:56






  • 1





    For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

    – max
    Nov 16 '18 at 14:59











  • Thanks! I might need to go through my project and see where else i can use map instead of each haha

    – RickS
    Nov 16 '18 at 15:04


















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





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339960%2fhow-can-i-create-json-array-of-json-objects-in-ruby-from-a-loop%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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 (and know what you are doing).






    share|improve this answer























    • What do you mean by 'side effects of the loop'?

      – RickS
      Nov 16 '18 at 14:56






    • 1





      For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

      – max
      Nov 16 '18 at 14:59











    • Thanks! I might need to go through my project and see where else i can use map instead of each haha

      – RickS
      Nov 16 '18 at 15:04















    2














    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 (and know what you are doing).






    share|improve this answer























    • What do you mean by 'side effects of the loop'?

      – RickS
      Nov 16 '18 at 14:56






    • 1





      For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

      – max
      Nov 16 '18 at 14:59











    • Thanks! I might need to go through my project and see where else i can use map instead of each haha

      – RickS
      Nov 16 '18 at 15:04













    2












    2








    2







    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 (and know what you are doing).






    share|improve this answer













    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 (and know what you are doing).







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 16 '18 at 14:54









    maxmax

    46.7k1060106




    46.7k1060106












    • What do you mean by 'side effects of the loop'?

      – RickS
      Nov 16 '18 at 14:56






    • 1





      For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

      – max
      Nov 16 '18 at 14:59











    • Thanks! I might need to go through my project and see where else i can use map instead of each haha

      – RickS
      Nov 16 '18 at 15:04

















    • What do you mean by 'side effects of the loop'?

      – RickS
      Nov 16 '18 at 14:56






    • 1





      For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

      – max
      Nov 16 '18 at 14:59











    • Thanks! I might need to go through my project and see where else i can use map instead of each haha

      – RickS
      Nov 16 '18 at 15:04
















    What do you mean by 'side effects of the loop'?

    – RickS
    Nov 16 '18 at 14:56





    What do you mean by 'side effects of the loop'?

    – RickS
    Nov 16 '18 at 14:56




    1




    1





    For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

    – max
    Nov 16 '18 at 14:59





    For example in ERB templates you use .each since you are outputting to a string buffer and the return value is not used.

    – max
    Nov 16 '18 at 14:59













    Thanks! I might need to go through my project and see where else i can use map instead of each haha

    – RickS
    Nov 16 '18 at 15:04





    Thanks! I might need to go through my project and see where else i can use map instead of each haha

    – RickS
    Nov 16 '18 at 15:04













    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





    share|improve this answer



























      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





      share|improve this answer

























        1












        1








        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





        share|improve this answer













        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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 14:54









        luisenrikeluisenrike

        1,884919




        1,884919



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339960%2fhow-can-i-create-json-array-of-json-objects-in-ruby-from-a-loop%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Top Tejano songwriter Luis Silva dead of heart attack at 64

            政党

            天津地下鉄3号線