簡體   English   中英

Ruby 返回除非塊

[英]Ruby return unless block

我有一個來自 github webhook 的字段 - webhook.repository.private - 它檢查創建的存儲庫是否是私有的(布爾值)。 我想使用return if塊來處理場景:檢查webhook.repository.private是否為真,如果不是則調用新的 class PublicRepositoryCreated但如果為真 - 返回並執行fields_hash

下面的代碼:

      def required_fields
        PublicRepositoryCreated.new(webhook).call unless webhook.repository.private

        fields_hash
      end

      private

      def fields_hash
        {
          'fields' => {
            'summary' => 'summary',
            'description' => 'description',
            'project' => '123'
          }
        }
      end

現在看來,即使webhook.repository.privatefalsefields_hash仍會執行

你有多種方法來解決你的問題。

您可以:

  1. 致電您的 function 並返回
def required_fields
  PublicRepositoryCreated.new(webhook).call && return unless webhook.repository.private

  fields_hash
end
  1. 返回您的 function
def required_fields
  return PublicRepositoryCreated.new(webhook).call unless webhook.repository.private

  fields_hash
end
  1. 使用三元
def required_fields
  webhook.repository.private ? fields_hash : PublicRepositoryCreated.new(webhook).call
end

暫無
暫無

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

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