Sort an array of Ruby homebrew classes

Sort an array of Ruby homebrew classes

** A new engineer (8th day) who will be one serving in 100 days **

How do you sort the array containing your own classes ... I got stuck a little today, so I'll leave it as a memo.

Homebrew class

user.rb


class User
  attr_accessor :name, :age, :height

  def initialize(name, age, height)
    @name = name
    @age = age
    @height = height
  end
end

user1 = User.new("foo", 15, 190)
user2 = User.new("bar", 80, 150)
user3 = User.new("baz", 28, 168)
users = [user1, user2, user3]

Create your own user classes like this and put them in an array called users Think about this sort of users today

** Try sorting for the time being **

ruby.rb


users.sort
#An error has occured
#`sort': comparison of User with User failed (ArgumentError)

I get angry as above. Failed to compare Users. You can't compare objects as they are.

So we will compare by the attribute of the object. To do this, use sort_by instead of the sort method. ** Compare by age **

ruby.rb


users = users.sort_by{|user|user.age}  #ascending order
p users.map{|user|"#{user.name},#{user.age},#{user.height}"}
#output["foo,15,190", "baz,28,168", "bar,80,150"]

users = users.sort_by{|user|user.age}.reverse  #descending order
#output["bar,80,150", "baz,28,168", "foo,15,190"]

I was able to sort by the attributes of my class like this. If you want to sort in descending order, use the reverse method for simplicity. Also, the sort_by method is easier to apply, so

ruby.rb


users = users.sort_by(&:height)

With this one line, you can sort the users in the users array in ascending order of height. Ruby is amazing, isn't it?

That's all for today. Thank you for watching.

** 92 days to become a full-fledged engineer **

Recommended Posts

Sort an array of Ruby homebrew classes
[Ruby] Array
12 of Array
Compare the elements of an array (Java)
Convert an array of strings to numbers
[Ruby] Get unique elements from an array
Basics of Ruby
Ruby two-dimensional array
Ruby array manipulation
How to request by passing an array to the query with HTTP Client of Ruby
[Ruby] Classes and instances
Ruby Learning # 29 Classes & Objects
definition of ruby method
Ruby classes and instances
[Ruby] Count an even number in an array using the even? Method
[Ruby] Searching for elements in an array using binary search
How to change a string in an array to a number in Ruby
How to retrieve the hash value in an array in Ruby
[Ruby] Creating code using the concept of classes and instances
Impressions and memories of openssl, curl, ruby, homebrew, rbenv installation
Install Ruby 3.0.0 Preview 1 with a combination of Homebrew and rbenv
Generate Stream from an array of primitive types in Java
[Ruby] How to batch convert strings in an array to numbers