Mark Locklear
Mark Locklear

Reputation: 5325

Test if elements of one array are included in another

I have the following arrays:

passing_grades = ["A", "B", "C", "D"]
student2434 = ["F", "A", "C", "C", "B"]

and I need to verify that all elements in the student array are included in the passing_grades array. In the scenario above, student2434 would return false. But this student:

student777 = ["C", "A", "C", "C", "B"]

would return true. I tried something like:

if student777.include? passing_grades then return true else return false end

without success. Any help is appreciated.

Upvotes: 6

Views: 145

Answers (2)

Iuri G.
Iuri G.

Reputation: 10630

PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  (grades - PASSING_GRADES).empty?
end

similar to what CDub had but without bug. more readable in my opinion

Upvotes: 9

CDub
CDub

Reputation: 13344

You could have a method that does the difference of the arrays, and if any results are present, they didn't pass:

PASSING_GRADES = ["A", "B", "C", "D"]

def passed?(grades)
  grades.all? {|grade| PASSING_GRADES.include?(grade)}
end

Example:

1.9.3-p484 :117 > student777 = ["C", "A", "C", "C", "B"]
 => ["C", "A", "C", "C", "B"] 
1.9.3-p484 :118 > passed?(student777)
 => true
1.9.3-p484 :118 > passed?(student2434)
 => false

Upvotes: 7

Related Questions