trueCamelType trueCamelType - 3 months ago 11
MySQL Question

Ruby sort_by from date formatted as string

I have a database that has a

task
table. In that table, there is a
date
column. Those dates are formatted as strings, they aren't
Date
.

I'm trying to sort these tasks by date. I already have an array of the tasks named
tasks
. I'm trying to replace it with the sorted array called
tasksByDate
using the below code.

tasksByDate = tasks.sort_by do |tasks|
task[:date].to_date
end


The error I'm getting is:

TypeError: no implicit conversion of Symbol into Integer


I also tried without
to_date
just to see if it would sort it without it being a date, and just being a string.

The
date
field is formatted as a string like so
2016-08-29
. I used the
to_date
method on it somewhere else in the code, and it works great, so I didn't really think that was the problem.




Edit 1

I have checked that tasks actually contains a date, and it is formatted like explained.

The output of
p task.class
is
Array


Edit 2

The output of
p task
is

[#<User id: 10, login: "my.name", hashed_password: "", date: "2016-08-29">]

Answer

The elements appear to be nested deeper than you expected them to be. Change the your code to:

# use '{ }' instead of 'do end' for a single-line blocks
tasksByDate = tasks.sort_by { |task| task.first[:date].to_date }

Explanation:

What you see as an output of p task:

[#<User id: 10, login: "my.name", hashed_password: "", date: "2016-08-29">]

It means that this is an Array of elements. Notice the enclosing braces [ ]. So what you have to do in this case is task.first, which will return:

 #<User id: 10, login: "my.name", hashed_password: "", date: "2016-08-29">

From there you should be able to access the element's values by a key, like you intended:

task.first[:date]