簡體   English   中英

如何選擇多個條件以返回與這些條件匹配的一個對象

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

我正在創建一個測試,並嘗試創建一種方法,當它與職位發布標題、職位類型和描述匹配時提取特定職位發布 ID,以防萬一有多個職位發布同名。

我無法使用select語句從實例變量中提取職位發布 ID。 調試顯示確實有ID嵌套在實例變量中,但我的條件沒有得到滿足,因為我沒有正確執行。

@job_posting是包含我需要的 ID 的實例變量,但我需要在 select 中匹配我的參數,以便我隨后可以返回 ID。

每當我只使用發布標題時,例如:

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

它可以工作並返回我需要的 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 它的工作原理相同,只是它會在找到第一個匹配項后立即停止迭代並返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM