stewart715
stewart715

Reputation: 5647

matching array items in rails

I have two arrays and I want to see the total number of matches, between the arrays individual items that their are.

For example arrays with:

1 -- House, Dog, Cat, Car 2 -- Cat, Book, Box, Car

Would return 2.

Any ideas? Thanks!

EDIT/

Basically I have two forms (for two different types of users) that uses nested attributes to store the number of skills they have. I can print out the skills via

current_user.skills.each do |skill| skill.name

other_user.skills.each do |skill| skill.name

When I print out the array, I get: #<Skill:0x1037e4948>#<Skill:0x1037e2800>#<Skill:0x1037e21e8>#<Skill:0x1037e1090>#<Skill:0x1037e0848>

So, yes, I want to compare the two users skills and return the number that match. Thanks for your help.

Upvotes: 1

Views: 518

Answers (1)

Gazler
Gazler

Reputation: 84140

This works:

a = %w{house dog cat car}
b = %w{cat book box car}
(a & b).size

Documentation: http://www.ruby-doc.org/core/classes/Array.html#M000274

To convert classes to an array using the name, try something like:

class X
  def name
    "name"
  end
end
a = [X.new]
b = [X.new]
(a.map{|x| x.name} & b.map{|x| x.name}).size

In your example, a is current_user.skills and b is other_users.skills. x is simply a reference to the current index of the array as the map action loops through the array. The action is documented in the link I provided.

Upvotes: 6

Related Questions