如何将多个条件的 select 转换为符合这些条件的 return 一个 object

How to select for multiple conditions to return one object that matches those conditions

我正在创建一个测试,并尝试创建一种方法,当它与职位发布标题、职位类型和描述相匹配时,它会提取一个特定的职位发布 ID,以防万一有更多而不是一个具有相同标题的职位发布。

我无法使用 select 语句从实例变量中提取职位发布 ID。调试发现实例变量中确实嵌套了ID,但是我的条件不满足,因为我做的不对。

@job_posting 是包含我需要的 ID 的实例变量,但我需要 select 中的参数匹配,以便我随后可以 return ID。

每当我只使用发帖标题时,例如:

target_postings = @job_postings.select{|posting|posting[:posting_title]}

有效,return是我需要的 ID,但是我不能这样做:

def get_specific_posting_id_for_posting(posting_title, job_type, description)
  expect(@job_postings.length > 0)
  target_postings = @job_postings.select {|posting| posting[:posting_title] == posting_title; posting[:job_type] == job_type; posting[:description] == description}
  expect(target_postings.length == 1)
  target_posting = target_postings[0]
  posting_id = target_posting[:posting_id]
  posting_id
end

看起来像

target_postings = @job_postings.select {|posting| posting[:posting_title] == posting_title; posting[:job_type] == job_type; posting[:description] == description}

应该是

target_postings = @job_postings.select do |posting| 
  posting[:posting_title] == posting_title 
    && posting[:job_type] == job_type 
    && posting[:description] == description
end

您的版本有三个独立的检查,前两个什么都不做,实际上只有块中的最后一个语句用于确定项目是否匹配。

顺便说一句,由于看起来您只需要符合条件的第一个元素,因此您可能需要考虑使用 find 而不是 select。它的工作原理是一样的,只是它会停止迭代,并且一旦找到第一个匹配项就会 return。