Do this in a single pass?
while(i < bArray.length)
if(aArray.include?(bArray[i]) == false) then
return false
end
i+=1
end
I've written the above but I find it to be ugly and bloated. There must be a clean cut开发者_StackOverflow社区 way to do this in a single statement.. but how?
This should be equivalent:
while i < bArray.length
return false unless aArray.include?(bArray[i])
i += 1
end
Here's a one-liner that I think should be equivalent:
bArray.all? { |item| aArray.include?(item) }
It looks like you're trying to find out if aArray contains all the elements of bArray.
aArray = %w[a b c d]
bArray = %w[a b c z]
(bArray - aArray).empty? # => false
I looked at the original code closer and it's got a logic bomb ticking:
def cmp_array(aArray, bArray)
i = 0
while (i < bArray.length)
if (aArray.include?(bArray[i]) == false) then
return false
end
i += 1
end
end
def cmp_array2(a, b)
(b - a).empty?
end
cmp_array( %w[ a b c ], %w[ a b c ]) # => nil
cmp_array( %w[ a b c ], %w[ c b a ]) # => nil
cmp_array( %w[ a b c ], %w[ a b ]) # => nil
cmp_array( %w[ a b c ], %w[ a b c d ]) # => false
cmp_array( %w[ a b ], %w[ a b c ]) # => false
cmp_array2( %w[ a b c ], %w[ a b c ]) # => true
cmp_array2( %w[ a b c ], %w[ c b a ]) # => true
cmp_array2( %w[ a b c ], %w[ a b ]) # => true
cmp_array2( %w[ a b c ], %w[ a b c d ]) # => false
cmp_array2( %w[ a b ], %w[ a b c ]) # => false
I had to add the i = 0
initializer otherwise Ruby complained about the uninitialized variable.
Notice that cmp_array
returns either nil or false, forcing an additional test for nil?
or false?
to do something useful.
if (cmp_array( %w[ a b c ], %w[ a b c ]).nil?) ...
or:
if (cmp_array( %w[ a b c ], %w[ a b c d ]).false?) ...
compared to:
if (cmp_array2( %w[ a b c ], %w[ a b c ])) ...
which consistently returns true/false.
bArray.all?(&aArray.method(:include?))
精彩评论