ruby检查数组中的任何项是否存在于另一个数组中

时间:2016-06-26 22:28:22

标签: arrays ruby

目前我有这段代码:

if !(allowed_params & password_protected_params).empty?

这意味着“如果allowed_pa​​rams中的任何内容也在password_protected_pa​​rams中”。这段代码有效,但我发现它有点混淆,对下一个查看此代码的开发人员不友好。

是否有另一种更易读的方法来检查另一个数组中是否存在一个数组中的任何内容?

修改

有问题的是:

if !(allowed_params & password_protected_params).empty?
  result = @user.update_with_password(allowed_params)
else
  #only update trivial attributes
  result = @user.update_without_password(allowed_params)
end

最后我添加了一个变量以使其更具可读性(但仍然可以获得更好的建议):

needs_password = !(allowed_params & password_protected_params).empty?
if needs_password
  result = @user.update_with_password(allowed_params)
else
  #only update trivial attributes
  result = @user.update_without_password(allowed_params)
end

2 个答案:

答案 0 :(得分:1)

Array#&没有官方同义词。您可以将代码重构为另一种方法,并添加注释:

def intersects?(a, b)
 !(a & b).empty?
end

# ...
if intersects? allowed_params, password_protected_params
# ...

否则,您可能需要扩展Array类,并定义方法或向其添加alias_method

class Array
  alias_method :intersection, :&    

  def intersects?(array)
    !(self.intersection(array)).empty?
  end
end

[1, 2, 3].intersects? [3, 4, 5] # true

请记住,改变核心课程不是一种好习惯。

答案 1 :(得分:0)

一种红宝石方式可能是

foo = [1, 2]
=> [1, 2]
bar = [1, 3]
=> [1, 3]
baz = [5, 3]
=> [5, 3]

bar.any?{|element| foo.include?(element)}
=> true
baz.any?{|element| foo.include?(element)}
=> false