仅当存在所有数组元素时才返回true

时间:2018-03-02 14:51:39

标签: arrays ruby

我有以下数组[681, 845, 787, 681]。只有当681和845都存在时我才会返回true。我觉得这应该有用:

registered_courses # => [681, 845, 787, 681]
registered_courses.all? {[842, 681]} # => true

我原以为这会返回false,因为数组中不存在842。

5 个答案:

答案 0 :(得分:1)

两件事:

  1. 您错误地使用.all?
  2. 你的逻辑是落后的,你真的想测试你想要看的所有课程(例如[842,681])是否在registered_courses

    [842, 681].all? { |course| registered_courses.include?(course) }

答案 1 :(得分:1)

考虑以下因素:

courses = [842, 681]
registered_courses = [681, 845, 787, 681]

您可以使用all?方法撤消逻辑:

courses.all? { |course| registered_courses.include?(course) } 
# => false

Demonstration

或者您也可以-使用empty?

(courses - registered_courses).empty?

Demonstration

答案 2 :(得分:1)

非uniq元素版本:

a = [681, 845, 787, 681]
b = [681, 842]
a_mudasobwa = a.inject(Hash.new(0)){|h, el| h[el]+= 1; h}
b_mudasobwa = b.inject(Hash.new(0)){|h, el| h[el]+= 1; h}
p b_mudasobwa.all?{|k,v| a_mudasobwa[k] >= v} # => false

答案 3 :(得分:0)

另一种方法是使用&运算符,即

courses = [842, 681]
(courses & registered_courses) == courses

&只返回两个数组中共同的数据;如果这符合您的要求,那么您就得到了答案。

答案 4 :(得分:0)

您可以减去数组,这样您就知道哪些元素不存在:

a = [681, 845, 787, 681]
b = [681, 842]
b - a # => [842]
相关问题