How to not repeat code when looping over a data structure where a key's value can be a hash or multi-item array?Ruby - elegantly convert variable to an array if not an array alreadyHow to change Hash values?How do I search within an array of hashes by hash values in ruby?How can I delete one element from an array by valueHow do I clean a data with hash and array mixed?Rails says my array of hashes is a string; I need to loop over this arrayRuby, loop over array of variable names, apply method to each and replace variable valueRuby loop/inject data into array with hash keys with different data pointsHow to generate XML using Builder to loop over structures inside XMLHow to collapse a multi-dimensional array of hashes in Ruby?Ruby - iterate over array of irregularly repeating hashes

Why do we use a cylinder as a Gaussian surface for infinitely long charged wire?

Adjective for 'made of pus' or 'corrupted by pus' or something of something of pus

In native German words, is Q always followed by U, as in English?

How did installing this RPM create a file?

How hard is it to sell a home which is currently mortgaged?

What game is this character in the Pixels movie from?

Why do I need two parameters in an HTTP parameter pollution attack?

How exactly is a normal force exerted, at the molecular level?

Why do changes to /etc/hosts take effect immediately?

If two black hole event horizons overlap (touch) can they ever separate again?

How did Lefschetz do mathematics without hands?

Pairwise Scatter Plots with Histograms and Correlations

Do launching rockets produce a sonic boom?

Could the Q destroy the universe?

I'm reinstalling my Linux desktop, how do I keep SSH logins working?

Should I share with a new service provider a bill from its competitor?

How to answer "write something on the board"?

What are good ways to spray paint a QR code on a footpath?

Buliding a larger matrix from a smaller one

Details of video memory access arbitration in Space Invaders

Matrix decomposition

Boolean Difference with Offset?

What's the safest way to inform a new user of their password on an invite-only website?

How do I tell the reader that my character is autistic in Fantasy?



How to not repeat code when looping over a data structure where a key's value can be a hash or multi-item array?


Ruby - elegantly convert variable to an array if not an array alreadyHow to change Hash values?How do I search within an array of hashes by hash values in ruby?How can I delete one element from an array by valueHow do I clean a data with hash and array mixed?Rails says my array of hashes is a string; I need to loop over this arrayRuby, loop over array of variable names, apply method to each and replace variable valueRuby loop/inject data into array with hash keys with different data pointsHow to generate XML using Builder to loop over structures inside XMLHow to collapse a multi-dimensional array of hashes in Ruby?Ruby - iterate over array of irregularly repeating hashes






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a complex data structure that looks as follows:



ds1 =

'item1' =>

'value' => '1024',
'flavor' => %w(s m l xl),
'platform_version' => %w(7),
,
'item2' =>
[
'value' => '2000000',
'flavor' => %w(l xl),
'platform_version' => %w(7),
,

'value' => '1000000',
'flavor' => %w(s m),
'platform_version' => %w(6),
,],



I'm currently looping over this as follows:



ds1.each do |name, obj|
if obj.is_a?(Array)
# Found that the data structure has multiple scenarios for the same key and need to loop over each element
obj.each do |sub_obj|
next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
obj_func(name, sub_obj) # call a function here
end
else
# hash only has one element so treat normally, no need for another loop
next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
obj_func(name, sub_obj) # call a function here
end
end


Sometimes I have much more code that I need to execute and having to repeat it twice depending on whether the "obj" is an array or not just makes my code look busy/ugly. Is there a more elegant way to handle this?










share|improve this question






























    0















    I have a complex data structure that looks as follows:



    ds1 =

    'item1' =>

    'value' => '1024',
    'flavor' => %w(s m l xl),
    'platform_version' => %w(7),
    ,
    'item2' =>
    [
    'value' => '2000000',
    'flavor' => %w(l xl),
    'platform_version' => %w(7),
    ,

    'value' => '1000000',
    'flavor' => %w(s m),
    'platform_version' => %w(6),
    ,],



    I'm currently looping over this as follows:



    ds1.each do |name, obj|
    if obj.is_a?(Array)
    # Found that the data structure has multiple scenarios for the same key and need to loop over each element
    obj.each do |sub_obj|
    next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
    obj_func(name, sub_obj) # call a function here
    end
    else
    # hash only has one element so treat normally, no need for another loop
    next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
    obj_func(name, sub_obj) # call a function here
    end
    end


    Sometimes I have much more code that I need to execute and having to repeat it twice depending on whether the "obj" is an array or not just makes my code look busy/ugly. Is there a more elegant way to handle this?










    share|improve this question


























      0












      0








      0








      I have a complex data structure that looks as follows:



      ds1 =

      'item1' =>

      'value' => '1024',
      'flavor' => %w(s m l xl),
      'platform_version' => %w(7),
      ,
      'item2' =>
      [
      'value' => '2000000',
      'flavor' => %w(l xl),
      'platform_version' => %w(7),
      ,

      'value' => '1000000',
      'flavor' => %w(s m),
      'platform_version' => %w(6),
      ,],



      I'm currently looping over this as follows:



      ds1.each do |name, obj|
      if obj.is_a?(Array)
      # Found that the data structure has multiple scenarios for the same key and need to loop over each element
      obj.each do |sub_obj|
      next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
      obj_func(name, sub_obj) # call a function here
      end
      else
      # hash only has one element so treat normally, no need for another loop
      next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
      obj_func(name, sub_obj) # call a function here
      end
      end


      Sometimes I have much more code that I need to execute and having to repeat it twice depending on whether the "obj" is an array or not just makes my code look busy/ugly. Is there a more elegant way to handle this?










      share|improve this question
















      I have a complex data structure that looks as follows:



      ds1 =

      'item1' =>

      'value' => '1024',
      'flavor' => %w(s m l xl),
      'platform_version' => %w(7),
      ,
      'item2' =>
      [
      'value' => '2000000',
      'flavor' => %w(l xl),
      'platform_version' => %w(7),
      ,

      'value' => '1000000',
      'flavor' => %w(s m),
      'platform_version' => %w(6),
      ,],



      I'm currently looping over this as follows:



      ds1.each do |name, obj|
      if obj.is_a?(Array)
      # Found that the data structure has multiple scenarios for the same key and need to loop over each element
      obj.each do |sub_obj|
      next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
      obj_func(name, sub_obj) # call a function here
      end
      else
      # hash only has one element so treat normally, no need for another loop
      next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
      obj_func(name, sub_obj) # call a function here
      end
      end


      Sometimes I have much more code that I need to execute and having to repeat it twice depending on whether the "obj" is an array or not just makes my code look busy/ugly. Is there a more elegant way to handle this?







      ruby






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 13:40







      sconicelli

















      asked Mar 25 at 13:25









      sconicellisconicelli

      496 bronze badges




      496 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          2














          You could just wrap it in an array all the time:



          ds1.each do |name, obj|
          [obj].flatten(1).each do |sub_obj|
          next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
          obj_func(name, sub_obj) # call a function here
          end
          end





          share|improve this answer

























          • I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

            – sconicelli
            Mar 25 at 14:07











          • @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

            – spickermann
            Mar 25 at 14:23











          • Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

            – sconicelli
            Mar 25 at 14:34











          • You can replace [obj].flatten(1) with Array(obj) or [*obj].

            – Cary Swoveland
            Mar 31 at 2:52











          • @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

            – spickermann
            Mar 31 at 5:22










          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%2f55338868%2fhow-to-not-repeat-code-when-looping-over-a-data-structure-where-a-keys-value-ca%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          You could just wrap it in an array all the time:



          ds1.each do |name, obj|
          [obj].flatten(1).each do |sub_obj|
          next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
          obj_func(name, sub_obj) # call a function here
          end
          end





          share|improve this answer

























          • I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

            – sconicelli
            Mar 25 at 14:07











          • @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

            – spickermann
            Mar 25 at 14:23











          • Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

            – sconicelli
            Mar 25 at 14:34











          • You can replace [obj].flatten(1) with Array(obj) or [*obj].

            – Cary Swoveland
            Mar 31 at 2:52











          • @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

            – spickermann
            Mar 31 at 5:22















          2














          You could just wrap it in an array all the time:



          ds1.each do |name, obj|
          [obj].flatten(1).each do |sub_obj|
          next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
          obj_func(name, sub_obj) # call a function here
          end
          end





          share|improve this answer

























          • I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

            – sconicelli
            Mar 25 at 14:07











          • @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

            – spickermann
            Mar 25 at 14:23











          • Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

            – sconicelli
            Mar 25 at 14:34











          • You can replace [obj].flatten(1) with Array(obj) or [*obj].

            – Cary Swoveland
            Mar 31 at 2:52











          • @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

            – spickermann
            Mar 31 at 5:22













          2












          2








          2







          You could just wrap it in an array all the time:



          ds1.each do |name, obj|
          [obj].flatten(1).each do |sub_obj|
          next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
          obj_func(name, sub_obj) # call a function here
          end
          end





          share|improve this answer















          You could just wrap it in an array all the time:



          ds1.each do |name, obj|
          [obj].flatten(1).each do |sub_obj|
          next unless flavor_check?(sub_obj, s_lit, 'flavor') # calls flavor_check? function
          obj_func(name, sub_obj) # call a function here
          end
          end






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 25 at 14:21

























          answered Mar 25 at 13:51









          spickermannspickermann

          63.9k7 gold badges61 silver badges84 bronze badges




          63.9k7 gold badges61 silver badges84 bronze badges












          • I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

            – sconicelli
            Mar 25 at 14:07











          • @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

            – spickermann
            Mar 25 at 14:23











          • Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

            – sconicelli
            Mar 25 at 14:34











          • You can replace [obj].flatten(1) with Array(obj) or [*obj].

            – Cary Swoveland
            Mar 31 at 2:52











          • @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

            – spickermann
            Mar 31 at 5:22

















          • I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

            – sconicelli
            Mar 25 at 14:07











          • @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

            – spickermann
            Mar 25 at 14:23











          • Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

            – sconicelli
            Mar 25 at 14:34











          • You can replace [obj].flatten(1) with Array(obj) or [*obj].

            – Cary Swoveland
            Mar 31 at 2:52











          • @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

            – spickermann
            Mar 31 at 5:22
















          I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

          – sconicelli
          Mar 25 at 14:07





          I tried this before but since "obj" is a hash, I think I am running into something similar to stackoverflow.com/questions/18358717/…

          – sconicelli
          Mar 25 at 14:07













          @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

          – spickermann
          Mar 25 at 14:23





          @sconicelli You are right. I wasn't aware of this edge case. I changed my answer to that suggested version from the other question which I liked best.

          – spickermann
          Mar 25 at 14:23













          Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

          – sconicelli
          Mar 25 at 14:34





          Thanks! made sense for me to just extend Array like rails does... not sure why Ruby itself doesn't add this feature. Problem solved though...

          – sconicelli
          Mar 25 at 14:34













          You can replace [obj].flatten(1) with Array(obj) or [*obj].

          – Cary Swoveland
          Mar 31 at 2:52





          You can replace [obj].flatten(1) with Array(obj) or [*obj].

          – Cary Swoveland
          Mar 31 at 2:52













          @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

          – spickermann
          Mar 31 at 5:22





          @CarySwoveland: Unfortunately, Array(obj) or [*obj] doesn't work in this example, because here the single element would be a hash and the expected the response would be an array with one hash inside. But instead, an array of arrays is returned. See: stackoverflow.com/q/18358717/2483313

          – spickermann
          Mar 31 at 5:22








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          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%2f55338868%2fhow-to-not-repeat-code-when-looping-over-a-data-structure-where-a-keys-value-ca%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript