** 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.
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