2016-11-02 4 views
-1

Защитукомплекс массив хэшей с помощью рубин

twitter_data 
    [{"LaunchAcademy"=> 
    {"description"=> 
    "A 10 week, intensive bootcamp teaching you how to code with a focus on Ruby on Rails", 
    "last twenty tweets"=> 
    ["RT @chrisccerami: While learning web development I created a map of all of the shows @Screamales have played and damn @DonGiovanniRecs http…", 
     "6 ways to quantify your code and why you need to do it: by @kevinrcasey , 
     "Do more of what you want at work. How to create productive partnerships: by @benvoss", 
     "RT @Pistachio: SO rad. bunch of local women learning to code with @gdiBoston at @HubSpot right now: , 
     "RT @STWatkins78: Huge breakthrough on my breakable toy today...can upload local file to soundcloud from my app...time for a beer! #LaunchAc…", 
     "Just say yes to opportunities, especially if they scare you. great advice by @kerry_benjamin1", 
     "How the internet is changing software and business, using Ruby as an example: by @ukitazume , 
     "RT @chrisccerami: @JustusEapen @LaunchAcademy @MarsCuriosity , 
     "Come build some interesting projects! @womenwhocode Hack Night tomorrow. RSVP:, 
     "RT @SpencerCDixon: One of the greatest parts of being a developer is the massive amount of control you have over a computer. Feels very emp…", 
     "7 reasons to love Minitest for testing Ruby code: by @FluxusFrequency, a graduate from our friends @gschool", 
     "Interested in becoming a game developer? Here's how: via @skilledup , 
     "Web developer hiring trends, and what they mean for you: by @walesmd , 
     "RT @chrisccerami: I recently built my first API in Rails which I hope makes photos from Mars courtesy of @MarsCuriosity more accessible to …", 
     "Build things that last. Make sure your work lives beyond you. by @acolangelo", 
     "Thanks to everyone who came to Ship It! Saturday! Check out the latest blog post for a recap:, 
     "Write your code as if your best friend's inheriting it by @MGraybosch, 
     "Coding can improve the way we run the world. Old, but inspiring TED talk by @pahlkadot: , 
     "Practicing pitches and getting ready for Career Day, coming up on January 27th and 28th! , 
     "RT @lizvdk: The cool kids use GEOjson so I did too. Here's how I build it with Ruby: ], 
    "number of followers"=>3590, 
    "number of friends"=>699, 
    "latest tweet"=> 
    "RT @chrisccerami: While learning web development I created a map of all of the shows @Screamales have played and damn @DonGiovanniRecs http…", 
    "number of tweets"=>1433, 
    "location"=>"Boston, MA"}}, 
{"dpickett"=> 
    {"description"=>"Co-Founder at @LaunchAcademy, Co-Organizer of @bostonrb", 
    "last twenty tweets"=> 
    ["RT @MeetingBoy: If your employees worked until 3AM, you have failed as a manager.", 
     "Glad to see two organizations that are near and dear to me (@EntrepreneurOrg and @YEC) at the top of this list: , 
     "@lizvdk I had the same reaction - it was like they spent the last 45 minutes trolling the movie industry.", 
     "RIP @jamesgolick - I learned so much from you, and always thought you were one of the most professional and skilled devs I've ever met :-(", 
     "Aspiring devs, if you need an example of a professional that embodies all we try to teach and more, look to @hchood Thank you! I'll miss you", 
     "Some notes for my facilitation tomorrow on debugging JavaScript: , 
     "@marcomorawec and @kenmazaika great having you guys at Mission Control! Love meeting folks with their hearts in technical education :-)", 
     "RT @graysky: \"Resumes suck. Here’s the data.\" by @alinelernerLLC Most create similar, unhelpful resume", 
     "@paulanthonywils @searls @markbates I reported the @bostonrb imitator as spam. Seems like the right thing to do", 
     "@divineanimal @LaunchAcademy we're delighted to have you! :-) See you soon and keep us posted on how prelearning is going.", 
     "sad to hear about @ezmobius passing. His work at @engineyard and some of his conference talks blew my mind. A source of wisdom for many. RIP", 
     "Thank you! , 
     "@jboursiquot happy birthday man!", 
     "lol! the irony of this error message!, 
     "such refreshing honesty \"If you really believe that you and your business are one, business failure destroys you\, 
     "RT @bostonrb: Instead of our monthly meeting, we're going to party in December! Join us at the Black Rose on 12/9 @ 7PM. RSVP @ https://t.c…", 
     "@dan_kleiman @LaunchAcademy @heroiceric Mr. G is shedding a tear right now.", 
     "@kdaigle I always consider there to be a 2 or 3 year lag in enterprise adoption of ideas like that.", 
     "Change is good. \"Why Google doesn’t care about hiring top college graduates\" by @MaxNisen", 
     "This is why I can't read TechCrunch. What an uninformed piece, and a total misunderstanding of the term \"full stack\], 
    "number of followers"=>1604, 
    "number of friends"=>874, 
    "latest tweet"=> 
    "RT @MeetingBoy: If your employees worked until 3AM, you have failed as a manager.", 
    "number of tweets"=>3451, 
    "location"=>"ÜT: 42.132759,-71.132183"}}, 

Я понимаю, как назвать одну конкретную информацию для массива хэшей, что я изо всех сил на это сразу же получать от всех хэшей. Как я смогу распечатать каждого пользователя и их описание сразу? пример

LaunchAcademy: A 10 week, intensive bootcamp teaching you how to code with a 
    focus on Ruby on Rails 
    dpickett: Co-Founder at @LaunchAcademy, Co-Organizer of @bostonrb 
+0

Почему спешка, чтобы выбрать ответ? Вы всегда принимаете предложенную? –

ответ

0
twitter_data.each do |data| 
    puts "#{data.keys[0]}: #{data[data.keys[0]]['description']}" 
end 
0

Во-первых, давайте начнем с более разумного набора данных.

twitter_data = [ 
    { "LaunchAcademy"=>{ "description"=>"A 10 week, intensive bootcamp", 
         "last 2 tweets"=>["Hi ho", "Vote for a nasty person!"], 
         "number of friends"=>1 } }, 
    { "dpickett"=> { "description"=>"Co-Founder, Co-Organizer", 
         "last 2 tweets"=> ["How now, brown cow?", "Little Miss Muffet.."], 
         "number of friends"=>874 } } 
] 

Когда мы видим, что у нас есть, легко увидеть, как описания могут быть напечатаны на консоли.

Этапы заключаются в следующем. Первый элемент передается к блоку, и переменная блока h устанавливается равным этому элементу:

h = twitter_data.first 
    #=> {"LaunchAcademy"=>{"description"=>"A 10 week, intensive bootcamp", 
    #      "last 2 tweets"=>["Hi ho", "Vote for a nasty person!"], 
    #      "number of friends"=>1}} 

первый (и единственный) ключ-значение пары затем экстрагируют и блок переменных k и `v назначены ключ и значение, соответственно, с использованием параллельного присваивания (иногда называемый множественного присваивания):

k,v = h.first 
    #=> ["LaunchAcademy", 
    # {"description"=>"A 10 week, intensive bootcamp", 
    #  "last 2 tweets"=>["Hi ho", "Vote for a nasty person!"], 
    #  "number of friends"=>1}] 
k #=> "LaunchAcademy" 
v #=> {"description"=>"A 10 week, intensive bootcamp", 
    # "last 2 tweets"=>["Hi ho", "Vote for a nasty person!"], 
    # "number of friends"=>1} 

строка быть puts «под ред поэтому

"Description for #{k}: #{v["description"]}" 
    #=> "Description for LaunchAcademy: A 10 week, intensive bootcamp" 

Те же шаги выполняются для второго элемента twitter_data.

Смежные вопросы