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;
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
add a comment |
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
add a comment |
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
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
ruby
edited Mar 25 at 13:40
sconicelli
asked Mar 25 at 13:25
sconicellisconicelli
496 bronze badges
496 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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
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)
withArray(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
|
show 5 more comments
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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)
withArray(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
|
show 5 more comments
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
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)
withArray(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
|
show 5 more comments
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
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
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)
withArray(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
|
show 5 more comments
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)
withArray(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
|
show 5 more comments
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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