代码之家  ›  专栏  ›  技术社区  ›  Qiulang

如何在ruby中提前返回以减少嵌套if?

  •  1
  • Qiulang  · 技术社区  · 7 年前

    //instead of nested if like this 
    if (condition1) {
       if (condition2) {
         if (condition3) {
           //... finally meet all conditions 
           //do the job 
         }
       }
    }
    //return early 
    if (!condition1) {
       //clean up resource in step #1
       return
    }
    if (!condition2) {
       //clean up resource in step #2
       return
    }
    if (!condition3) {
       //clean up resource in step #2
       return
    }
    ...
    //finally meet all conditions 
    

    未捕获异常:意外返回…`block(2级)in':意外返回(LocalJumpError)

    ----更新-----

    def early(input)
      if (input <0)
        puts 'should >0'
        return
      end
      puts 'good'
    end
    

    我正在学习光纤,我使用来自 https://www.igvita.com/2010/03/22/untangling-evented-code-with-ruby-fibers/

    def http_get(url)
      f = Fiber.current
      http = EventMachine::HttpRequest.new(url).get
    
      # resume fiber once http call is done
      http.callback { f.resume(1,http) }
      http.errback  { f.resume(2,http) }
    
      return Fiber.yield
    end
    
    EventMachine.run do
      Fiber.new{
        result = http_get('https://www.google.com/')
        if (result[0] ==2) 
          puts "error"
          return # using break has the error 'break from proc-closure (LocalJumpError)' too 
        end
        result = http_get('https://www.google.com/search?q=eventmachine')
        page = result[1]
        puts "Fetched page 2: #{page.response}"
      }.resume
    end
    

    我弄错了。

    How can I return something early from a block?

    还有这个 Why does the break statement in ruby behave differently when using Proc.new v. the ampersand sign? 解释了为什么break也不起作用。引用“break应该使块的调用者返回,但是Proc.new已经返回。”

    对于一个ruby新手来说,返回vs中断vs下一个绝对是一个障碍

    1 回复  |  直到 7 年前
        1
  •  0
  •   user000001 jim mcnamara    7 年前

    使用 next 而不是 return 要提前退出内部块,请执行以下操作:

    class A 
      def run 
        yield
      end
    end
    
    a = A.new
    a.run do 
      puts "ola"
      next
      puts "hello"
    end
    

    为了使用 返回 ,它应该直接放在方法体内部。

    EventMachine.run do Fiber.new{ ,块内的代码不是直接在函数内,而是作为参数传递给另一个函数。在区块内,您无法调用 下一个 .

    返回 在块内部,将导致混淆块是返回还是返回整个方法。

    推荐文章