【问题标题】:Select item in array that matches one item in another array选择数组中与另一个数组中的一项匹配的项
【发布时间】:2014-03-28 09:33:24
【问题描述】:

问题: 从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] 中的每一项

【问题讨论】:

  • 如果我正确理解了这个问题,您可以执行cached.find { |email| params[:domain].include?(email.match(/@(.*)/)[1]) 之类的操作。让我知道这是否有效,因为我不确定这个问题

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


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多