选择数组中与另一个数组中的一个项匹配的项

时间:2014-03-28 09:33:24

标签: ruby-on-rails arrays where rails-activerecord

问题: 从contacts表中获取单个记录,其中first_namelast_name等于参数中给出的记录。如果找到多个记录,则返回与域匹配的记录。

def check_cache(params)
  cached = where(first_name: params[:first_name], last_name: params[:last_name])
  if cached.size > 1
    # select the record with a matching one of params[:domains]
    # cached #=> ['bob@gmail.com', 'bob@yahoo.com']
    # params[:domains] #=> ['gmail.com', 'abc.com']
    # result would be bob@gmail.com
  end
  cached
end

在IRB中尝试了这个

cached.select{|e| e =~ /(gmail.com)/}

但不确定如何检查params[:domains]

中的每一个

1 个答案:

答案 0 :(得分:2)

试试这个:

if cached.size > 1   
  params[:domains].each do |domain|
    cached.select do |result|
      result_domain = result.split("@").last

      return result if result_domain == domain
    end
  end
end