我有以下数组:
passing_grades = ["A", "B", "C", "D"]
student2434 = ["F", "A", "C", "C", "B"]
我需要验证student
数组中的所有元素都包含在passing_grades
数组中。在上面的场景中,student2434
将返回false。但是这个学生:
student777 = ["C", "A", "C", "C", "B"]
会返回true
。我试过像:
if student777.include? passing_grades then return true else return false end
没有成功。任何帮助表示赞赏。
答案 0 :(得分:9)
PASSING_GRADES = ["A", "B", "C", "D"]
def passed?(grades)
(grades - PASSING_GRADES).empty?
end
类似于CDub但没有bug。在我看来更具可读性
答案 1 :(得分:7)
您可以使用一种方法来处理数组的差异,如果存在任何结果,则它们不会通过:
PASSING_GRADES = ["A", "B", "C", "D"]
def passed?(grades)
grades.all? {|grade| PASSING_GRADES.include?(grade)}
end
示例:
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