Ruby how to find each value in hash greater than x?

Viewed 419

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
}
2 Answers

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 :)

Check select method with a block

months.select{|key, value| value > 30}
Related