Skip to content

Instantly share code, notes, and snippets.

@rjurney
Created November 11, 2010 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjurney/671889 to your computer and use it in GitHub Desktop.
Save rjurney/671889 to your computer and use it in GitHub Desktop.
How do I one-liner fill this hash in, so that there are no missing "start_years" ?
irb(main):168:0> records = experience_client.get('principal designer')['by_years']
=> [{"total"=>13, "start_years"=>0}, {"total"=>12, "start_years"=>1}, {"total"=>18, "start_years"=>2}, {"total"=>13, "start_years"=>3}, {"total"=>17, "start_years"=>4}, {"total"=>19, "start_years"=>5}, {"total"=>16, "start_years"=>6}, {"total"=>17, "start_years"=>7}, {"total"=>14, "start_years"=>8}, {"total"=>16, "start_years"=>9}, {"total"=>14, "start_years"=>10}, {"total"=>11, "start_years"=>11}, {"total"=>8, "start_years"=>12}, {"total"=>11, "start_years"=>13}, {"total"=>9, "start_years"=>14}, {"total"=>11, "start_years"=>15}, {"total"=>9, "start_years"=>16}, {"total"=>8, "start_years"=>17}, {"total"=>8, "start_years"=>18}, {"total"=>6, "start_years"=>19}, {"total"=>7, "start_years"=>20}, {"total"=>3, "start_years"=>21}, {"total"=>5, "start_years"=>22}, {"total"=>6, "start_years"=>23}, {"total"=>2, "start_years"=>24}, {"total"=>1, "start_years"=>27}, {"total"=>1, "start_years"=>28}, {"total"=>1, "start_years"=>29}, {"total"=>2, "start_years"=>30}, {"total"=>1, "start_years"=>31}, {"total"=>1, "start_years"=>34}, {"total"=>1, "start_years"=>42}]
@acrosa
Copy link

acrosa commented Nov 11, 2010

a hash with empty values

a = [{"total"=>13, "start_years"=>0}, {"total"=>12, "start_years"=>1}, {"total"=>18, "start_years"=>2}, {"total"=>13, "start_years"=>3}, {"total"=>17, "start_years"=>4}, {"total"=>19, "start_years"=>5}, {"total"=>16, "start_years"=>6}, {"total"=>17, "start_years"=>7}, {"total"=>14, "start_years"=>8}, {"total"=>16, "start_years"=>9}, {"total"=>14, "start_years"=>10}, {"total"=>11, "start_years"=>11}, {"total"=>8, "start_years"=>12}, {"total"=>11, "start_years"=>13}, {"total"=>9, "start_years"=>14}, {"total"=>11, "start_years"=>15}, {"total"=>8, "start_years"=>17}, {"total"=>8, "start_years"=>18}, {"total"=>6, "start_years"=>19}, {"total"=>7, "start_years"=>20}, {"total"=>3, "start_years"=>21}, {"total"=>5, "start_years"=>22}, {"total"=>6, "start_years"=>23}, {"total"=>2, "start_years"=>24}, {"total"=>1, "start_years"=>27}, {"total"=>1, "start_years"=>28}, {"total"=>1, "start_years"=>29}, {"total"=>2, "start_years"=>30}, {"total"=>1, "start_years"=>31}, {"total"=>1, "start_years"=>34}, {"total"=>1, "start_years"=>42}]

h = {}
a.map { |e| h[e["start_years"]] = e["total"] } # build a hash of values
(1..42).each { |i| puts h[i] || 0 } # iterate with the range you want

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment