2

I am bit new to Ruby and had a problem with learning hashes. I have hash which contains months and days inside this month. And I need to print each one that has 31 days.

months = {
  "MAR" => 31,
  'APR' => 30,
  'MAY' => 31,
  'JUN' => 30
}
Silka
  • 194
  • 2
  • 11

2 Answers2

5

You can use:

months.select { |_month, days| days > 30 }    

This former gives you all results that fit the criteria (days > 30).

Here are the docs:

Once you've got the values you need, you can then print them to the console (or output however you'd like), e.g.

long_months = months.select { |_month, days| days > 30 }
long_months.each { |month, days| puts "#{month} has #{days} days" }

All that being said, assigning to a value before printing the result means two loops, whereas this can be achieved in one using a simple each:

months.each do |month, days|
  puts("#{month} has #{days} days") if days > 30
end

That'll be more efficient as there's less churn involved :)

tadman
  • 208,517
  • 23
  • 234
  • 262
SRack
  • 11,495
  • 5
  • 47
  • 60
  • Thank you very much. Your last code is working and helped me a lot! – Silka Mar 22 '21 at 16:19
  • Great, very glad I could help @Silka :) If you feel you've got what you needed here and the answer filled the brief, I'd be grateful if you'd click the tick to accept. – SRack Mar 22 '21 at 16:20
1

Check select method with a block

months.select{|key, value| value > 30}
J.Krzus
  • 314
  • 3
  • 11