I have this array :
>> arr = [["a",1,"b"],["a",2,"b"],["b",3,"d"],["t",6,"a"]]
I want to check if ["a",1] exists inside the arr
while ignoring the 3rd value of the arr
items.
Is there a better way then first removing the 3rd value from each item in arr
:
>> new_arr = [["a",1],["a",2],["b",3],["t",6]]
and then doing
>> new_arr.include? ["a",1]
true
Something like:
arr.include? ["a",1,/*/] #the 3rd value can be anything
Thanks.
You can try the below :
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
wrap the logic inside a method :
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments