Sort a list of objects by using their attributes in Ruby
The easy solution is
basket.sort_by { |f| [-f.calories, f.name] }
Of course, if this is the canonical sort order for fruit then it should be defined using the <=>
method and with the Comparable
module mixed into Fruit
Sorting a hash table of objects (by the attributes of the objects) in Ruby
You appear to be confusing sort
and sort_by
sort
yields two objects from the collection to the block and expects you to return a <=> like value: -1,0 or 1 depending on whether the arguments are equal, ascending or descending, for example
%w(one two three four five).sort {|a,b| a.length <=> b.length}
Sorts the strings by length. This is the form to use if you want to use your <=> operator
sort_by
yields one object from the collection at a time and expects you to return what you want to sort by - you shouldn't be doing any comparison here. Ruby then uses <=> on these objecfs to sort your collection. The previous example can e rewritten as
%w(one two three four five).sort_by {|s| s.length}
This is also known as a schwartzian transform
In your case the collection is a hash so things are slightly more complicated: the values that are passed into the block are arrays that contain key/value pairs, so you'll need to extract the person object from that pair. You could also just work on @hash.keys or @hash.values (depending on whether the person objects are keys or values)
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
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
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
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
sorting a ruby array of objects by an attribute that could be nil
How about in Child
defining <=>
to be based on category.position
if category
exists, and sorting items without a category
as always greater than those with a category
?
class Child
# Not strictly necessary, but will define other comparisons based on <=>
include Comparable
def <=> other
return 0 if !category && !other.category
return 1 if !category
return -1 if !other.category
category.position <=> other.category.position
end
end
Then in Parent
you can just call children.sort
.
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
How to Make Xcode Use the Correct Version of Ruby When Running a Script
Why Do Ruby Procs/Blocks with Splat Arguments Behave Differently Than Methods and Lambdas
Listing Directories at a Given Level in Amazon S3
How to Stub a Method of an Included Module with Rspec
How to Evaluate a Date Difference in Years, Months and Days (Ruby)
Undefined Method Respond_To in Rails 5 Controller
Create Paperclip Attachment from Rmagick Image
Passing Params to Cancan in Ror
How to Input Multibyte Characters in Rails Console (Or Irb)
Sort Values Using a Specific Collation in Ruby/Rails
Ruby: Is Variable Is Object in Ruby
How to Remove Xcode 4.2 and Install 4.1 to Develop Ruby/Rails on Osx Lion
Why Will a Range Not Work When Descending