0

Given there are several users named A, A1, A2, A3, A4,and each user has some books.

A  has books: B1, B2, B3, B4, B5   
A1 has books: B2, B4  
A2 has books: B3, B4, B5, B6  
A3 has books: B1, B3, B5
A4 has books: B1, B6

The ruby/rails objects relations is:

+ User.class  
+ Book.class

A user has many books, and a book belongs to a user, so we have user.books, and book.user.

Question

The question is how to use Ruby to sort the users (A1,A2,A3,A4) by which has the most books in common with user A.

Result

The result should be [A2, A3, A1, A4] or something like that.

Hope you guys can help me to implements this algorithm with Ruby/ Rails.

1 Answer 1

3

I doubt that using constants in the way suggested by the OP is useful in any way because you have to look at the object id to tell which object is which, but to realize what the OP asked for:

class User; attr_accessor :books end
class Book end

B1 = Book.new
B2 = Book.new
B3 = Book.new
B4 = Book.new
B5 = Book.new
B6 = Book.new
A = User.new
A1 = User.new # => #<User:0x007f38ddb8a890>
A2 = User.new # => #<User:0x007f38ddb8a458>
A3 = User.new # => #<User:0x007f38ddb8a070>
A4 = User.new # => #<User:0x007f38ddb89c38>
A.books = [B1, B2, B3, B4, B5]
A1.books =[B2, B4]
A2.books =[B3, B4, B5, B6]
A3.books =[B1, B3, B5]
A4.books = [B1, B6]

[A1, A2, A3, A4].sort_by{|user| (user.books & A.books).length}.reverse

result

[
  #<User:0x007f38ddb8a070 @books=[#<Book:0x007f38ddb8a9d0>, #<Book:0x007f38ddb8a980>, #<Book:0x007f38ddb8a930>]>,
  #<User:0x007f38ddb8a458 @books=[#<Book:0x007f38ddb8a980>, #<Book:0x007f38ddb8a958>, #<Book:0x007f38ddb8a930>, #<Book:0x007f38ddb8a908>]>,
  #<User:0x007f38ddb8a890 @books=[#<Book:0x007f38ddb8a9a8>, #<Book:0x007f38ddb8a958>]>,
  #<User:0x007f38ddb89c38 @books=[#<Book:0x007f38ddb8a9d0>, #<Book:0x007f38ddb8a908>]>,
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.