Sorting an Array of Objects in Ruby by Object Attribute

Ruby - sort array of objects by attribute in descending order

You missed to make the age a number

@classroom['students'].sort_by { |st| -st['age'].to_i }

I added a - because you want them in descending order. Otherwise

@classroom['students'].sort_by { |st| st['age'].to_i }.reverse

How to sort an array of objects by an attribute of the objects?

I found a method that works from here. I don't understand what the "&" symbol is doing - maybe it's shorthad for "object" since in my case ":lastname" is an attribute of the object that make up the array.

users = users.sort_by &:lastname

note: I don't undertand why but a destructive version won't work. It produces a "undefined method `sort_by!' for #" errror:

users.sort_by! &:lastname

Sorting by an array's elements properties in ruby

sort_by is probably the shortest option

exarray.sort_by {|x| x.number}

This also works

exarray.sort_by &:number

Sorting an array of objects based on object property

Using sort_by

array.sort_by {|obj| obj.attribute}

Or more concise

array.sort_by(&:attribute)

In your case

array.sort_by {|obj| obj[:commit][:committed_date]}

Ruby sort by object's attribute based on keyword string

Try use public_send method

array.sort_by { |item| item.public_send(sort_keyword) } 

https://ruby-doc.org/core-2.4.1/Object.html#method-i-public_send

Sorting An Array of Object by Different Attributes

Assuming Opportunity and Recommendation should be sorted by opportunity_category.name and FastContent should be sorted by name, this would work:

@skills.sort_by { |skill|
case skill
when Opportunity, Recommendation
skill.opportunity_category.name
when FastContent
skill.name
end
}

Another option is to add a common method to all three classes:

class Opportunity < ActiveRecord::Base
def sort_name
opportunity_category.name
end
end

class Recommendation < ActiveRecord::Base
def sort_name
opportunity_category.name
end
end

class FastContent < ActiveRecord::Base
def sort_name
name
end
end

And use that instead:

@skills.sort_by(&:sort_name)

Sort objects in array by 2 attributes in Ruby with the spaceship operator

Define <=> like this:

   def <=>(other)
[str.size, str] <=> [other.str.size, other.str]
end

Ruby: Sort array of objects after an array of name properties

You can use Enumerable#sort_by

my_array.sort_by {|x| @sizes_sort_order.index(x.name) }

Sorting an array of objects by a child's attribute

collection.sort_by do |x|
x.children.where(:user_id => current_user.id).first.average_score
end

Though I'd look for a pure and faster SQL solution.



Related Topics



Leave a reply



Submit