vendredi 7 avril 2017

Ruby sort array with objects by first character of string

this is my first try using ruby, this is probably a simple problem, I have been stuck for an hour now, I have a ruby array with some objects in it, and I want that array to sort by the first character in the objects name property (which I make sure is always a number.)

the names are similar to:

4This is an option

3Another option

1Another one

0Another one

2Second option

I have tried:

objectArray.sort_by {|a| a.name[0].to_i}
objectArray.sort {|a,b| a.name[0].to_i <=> b.name.to_i}

In both cases my arrays sorting doesnt change.. (also used the destructive version of sort! and sort_by!)

I looped through the array like this:

objectArray.each do |test|
  puts test.name[0].to_i  
  puts "\n"
end

and sure enough I see the integer value it should have

Aucun commentaire:

Enregistrer un commentaire