检查部分值是否在数组内部

时间:2014-08-31 05:55:03

标签: ruby

我有这个数组:

>> arr = [["a",1,"b"],["a",2,"b"],["b",3,"d"],["t",6,"a"]]

我想检查arr内是否存在[“a”,1]而忽略arr项的第3个值。

是否有更好的方法,然后首先从arr中删除每个项目的第3个值:

>> new_arr = [["a",1],["a",2],["b",3],["t",6]]

然后做

>> new_arr.include? ["a",1]
true

类似的东西:

arr.include? ["a",1,/*/]  #the 3rd value can be anything

感谢。

3 个答案:

答案 0 :(得分:4)

您可以尝试以下方法:

arr = [["a",1,"b"],["a",2,"b"],["b",3,"d"],["t",6,"a"]]
arr.any? { |v1, v2, *| [v1, v2] == ["a", 1] }
# => true
arr.any? { |v1, v2, *| [v1, v2] == ["a", 4] }
# => false

包装方法中的逻辑:

def check_subarray(ary, sub_ary)
  ary.any? { |e1, e2, *| [e1, e2] == sub_ary }
end

arr = [["a",1,"b"],["a",2,"b"],["b",3,"d"],["t",6,"a"]]
check_subarray(arr, ["a", 1]) # => true

答案 1 :(得分:2)

这是@Arup的答案的更复杂版本(它处理任意长度)

def match_head(*head)
  ->(full_array) {
    head.each_with_index do |head_elem, idx|
      return false if full_array[idx] != head_elem
    end

    true
  }
end

ary = [["a",1,"b"],["a",2,"b"],["b",3,"d"],["t",6,"a"]]
ary.any?(&match_head('a')) # => true
ary.any?(&match_head('c')) # => false
ary.any?(&match_head('a', 1)) # => true
ary.any?(&match_head('a', 1, 'b')) # => true
ary.any?(&match_head('a', 1, 'f')) # => false

答案 2 :(得分:0)

另一种方式:

def values_there?(arr, val)
  arr.transpose[0,val.size].transpose.include? val
end

values_there?(arr, ["a", 2]) #=> true
values_there?(arr, [3, "d"]) #=> false