[2016-03-07] Challenge #257 [Easy] In what year were most presidents alive?

Ruby

Very, very new to both Ruby and programming in general, so any feedback or comments would be much appreciated. Daunted by the solutions I've seen!

require 'csv'

def presidents_alive(year_from, year_to)
  results = {}

  CSV.foreach("presidents.csv", encoding:"bom|utf-8", :headers => true, :header_converters => :symbol) do |row|    
    b = row[:birth_date][/\d{4}/].to_i
    d = row[:death_date][/\d{4}/] ? ( row[:death_date][/\d{4}/].to_i ) : 2016 

    (year_from..year_to).each do |year|
      results[year] ||= []
      results[year] << row[:president] if (b..d).include?(year)  
    end
  end
  return results
end

def most_in_year(results)
  results.each do |k,v|
    puts "#{k} - #{v.size} presidents alive" if v.size == (results.values.map {|i| i.size}).max
  end
end

most_in_year(presidents_alive(1733, 2016))

And - assuming I can get the markdown to work - this should be the output:

1822 - 18 presidents alive
1823 - 18 presidents alive
1824 - 18 presidents alive
1825 - 18 presidents alive
1826 - 18 presidents alive
1831 - 18 presidents alive
1833 - 18 presidents alive
1834 - 18 presidents alive
1835 - 18 presidents alive
1836 - 18 presidents alive
1837 - 18 presidents alive
1838 - 18 presidents alive
1839 - 18 presidents alive
1840 - 18 presidents alive
1841 - 18 presidents alive
1843 - 18 presidents alive
1844 - 18 presidents alive
1845 - 18 presidents alive

It's also capable (I think) of returning which presidents are alive on any given year

/r/dailyprogrammer Thread