簡體   English   中英

如何基於Ruby中的多個條件拒絕或選擇

[英]How to reject or select based on more than one condition in Ruby

我使用的API會根據情況返回不同的內容。

以下是該API可能返回的代碼段:

pages = [
  {
    'id' => 100,
    'content' => {
      'score' => 100
    },
  },
  {
    'id' => 101,
    'content' => {
      'total' => 50
    },
  },
  {
    'id' => 102,
  },
]

content是可選的,可以包含不同的項目。

我想返回score超過75的頁面列表。

到目前為止,這是我所能做到的:

pages.select! do |page|
  page['content']
end
pages.select! do |page|
  page['content']['score']
end
pages.select! do |page|
  page['content']['score'] > 75
end

如果我使用的是JavaScript,則可以執行以下操作:

pages.select(page => {
    if (!page['content'] || !page['content']['score']) {
        return false
    }
    return page['content']['score'] > 75
})

或者,如果我使用的是PHP,則可以用類似的方式來array_filter

但是,嘗試在Ruby中執行相同的操作會引發以下錯誤:

LocalJumpError: unexpected return

我明白你為什么不能這樣做 我只想找到一種在Ruby中實現此目標的簡單方法。


這是我想神奇地工作的Ruby:

pages = pages.select do |page|
  return unless page['content']
  return unless page['content']['score']
  page['content']['score'] > 75
end

您可以使用dig ,它可以訪問哈希中的嵌套鍵,如果它不能訪問至少其中之一,則返回nil,然后使用安全運算符進行比較:

p pages.select { |page| page.dig('content', 'score')&.> 75 }
# [{"id"=>100, "content"=>{"score"=>100}}]

請注意,此“過濾器”是一步完成的,因此您無需更改對象。

對於您的make-belive方法,您需要將next替換為return

pages = pages.select do |page|
  next unless page['content']
  next unless page['content']['score']
  page['content']['score'] > 75
end

p pages # [{"id"=>100, "content"=>{"score"=>100}}]

next用於跳過當前迭代的其余部分。


如果使用fetch並將空散列作為默認值傳遞,則可以在該示例中保存一行:

pages.select do |page|
  next unless page.fetch('content', {})['score']

  page['content']['score'] > 75
end

同樣的方法,您可以只執行page.fetch('content', {}).fetch('score', 0) > 75 (但最好不要這樣做)。

您實際上可以使用lambda實現此目的,其中return表示您期望的含義:

l = lambda do |page|
  return false if !page['content'] || !page['content']['score']

  page['content']['score'] > 75
end

pages.select(&l)
# => [{"id"=>100, "content"=>{"score"=>100}}]

但我想這不是很實用。

您可以使用邏輯“和”( && )來連接條件

pages.select! do |page|
  page['content'] && page['content']['score'] && page['content']['score'] > 75
end

暫無
暫無

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

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