Sorting numbers

I read a line from a CSV file as the following:
fooone,22,114,66,125,footwo
and I would like to sort the numbers from index
1 to 4, but I can’t convince the sort function
to work with integers instead of strings. The result
of sort is always 114,125,22,66 as it is sorted by
the first ASCII character.
The to_i function doesn’t seem to be appropiate.
Can the sort work with int’s or is only designed
to work with strings ?
I’m using Ruby 1.9.1 p378 with the ‘new’ built-in CSV.

Any clue welcomed, Andreu.

On 02/13/2010 10:18 AM, Andreu wrote:

I’m using Ruby 1.9.1 p378 with the ‘new’ built-in CSV.
There are two options:

  1. if you want to process the data further, first convert values from
    string to int. Then sorting will work as you expect.

  2. if you only want to sort them (e.g. for printing) please have a look
    at #sort_by.

Kind regards

robert

Thanks Robert and Raul. Both solutions worked.
I have finally used: row[1…4].sort_by {|a| a.to_i}

Regards, Andreu.

Andreu wrote:

I read a line from a CSV file as the following:
fooone,22,114,66,125,footwo
and I would like to sort the numbers from index
1 to 4, but I can’t convince the sort function
to work with integers instead of strings. The result
of sort is always 114,125,22,66 as it is sorted by
the first ASCII character.
The to_i function doesn’t seem to be appropiate.
Can the sort work with int’s or is only designed
to work with strings ?
I’m using Ruby 1.9.1 p378 with the ‘new’ built-in CSV.

Any clue welcomed, Andreu.

Why to you feel .to_i isn’t appropriate.

[“22”, “114”, “66”, “125”].sort{|a, b| a.to_i <=> b.to_i}

results in

[“22”, “66”, “114”, “125”]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs