I have an array of users which may or may not have an array of startups. The startup object has a property name.
I want to sort the array of users by the name of the startup. But I obviously get an error when the user object does have a startup.
I tried the following code after going through some of the solutions on StackOverflow. I'm using HAML thats why no "end" keyword
- @users.sort do |a, b|
- a.startup.nil? ? -1 : b.startup.nil? ? 1 : a.startup[0].name <=> b. startup[0].name
but I got the following error.
undefined method `name' for nil:NilClass
On trying
- @users.sort do |a, b|
- a.startup[0].nil? ? -1 : b.startup[0].nil? ? 1 : a.startup[0].name <=> b. startup[0].name
The users array was not sorted at all.
Note: I referred to this SO post Sorting an array of arrays in Ruby
I also tried
-@users.sort{|a,b| a.startup[0].name && b.startup[0].name ? a.startup[0].name <=> b.startup[0].name : a.startup[0].name ? -1 : 1 }
which is essentially
foo.sort{|a,b| a && b ? a <=> b : a ? -1 : 1 }
from the SO entry: sorting a ruby array of objects by an attribute that could be nil
even this gave the error
undefined method `name' for nil:NilClass
EDIT: When the user does not have a startup, I want that user to be placed at the end of the array.