How to compare dates that come from a CSV file in Ruby

Asked

Viewed 347 times

2

Good staff I have a CSV file with some data on it in case this:

Nome; Data; Salario

JOANNA  1981-04-11  7519.07
LUCIMAR 1958-06-10  819.77
PEDRO   1976-05-11  83.43    
JOAO    1989-03-12  867.5    
CAIO    1954-02-13  88.6   
JULIANA 1958-07-15  884.78    
LUCIMAR 1958-02-16  894.7

I wanted to know how to compare these two dates and know which is the biggest and the smallest and also know the names of people who were born on the same date someone can give me a light. I know that when I read the CSV file the data comes in an array so I am not able to compare the same who can help thank.

1 answer

2


David, the general idea of what you have to do to achieve your goals is to first process the data:

  1. Read data from data.csv file
  2. Throw out the first two lines
  3. Convert each String to an Array with 3 Strings
  4. Filter the data you want: Leave the name of the people, convert the String with the date to a Date type Object, send the numbers away.

Once the data is filtered, we just need to sort/group it the way we want it.

The snippet that solves your problem is this:

require 'date'

# Ler e formatar dados
formated_data = File.readlines('data.csv')[2..-1]
  .map { |line| line.split()  }
  .map { |fields| [fields[0], Date.parse(fields[1])] }

# Agrupar e ordenar dados
# Maior data:
p formated_data.max_by{ |fields| fields[1] }

# Menor data:
p formated_data.min_by{ |fields| fields[1] }

# Pessoas nasceram na mesma data
p formated_data.group_by { |fields| fields[1] }

Now let’s see what makes each line:

Now that you have the data turned into objects, it’s easy to transform it so that they group/filter in the way that they answer your questions:

  1. To get the maximum date, just say that you want the maximum of the array with the method #max_by and applies it to the second array field ( the one with the date) . Docs: max_by

  2. The same thing to get the bare minimum, but use the method instead #min_by. Docs: min_by

  3. Finally to group by date, use the #group_by method. Docs: #group_by

Browser other questions tagged

You are not signed in. Login or sign up in order to post.