这段代码片段有更好的做法吗?

时间:2012-02-19 14:38:12

标签: ruby return-value block watir

class MyWatir < Watir::Browser
  def with_watir_window(win)
    cw = window   #current window
    win.use
    yield
    cw.use
  end
  def qty     
    ret = nil                
    with_watir_window(@win2){
      ret = td(:id,'qty').text
    }      
    ret
  end 
end

在第二个函数中,声明ret = nil并在最后声明它似乎很难看。是否有更清晰的方法来返回值?

1 个答案:

答案 0 :(得分:8)

只需从块中返回内部值即可。还要确保如果发生异常,则保持一致状态:

class MyWatir < Watir::Browser
  def with_watir_window(win)
    cw = window   #current window
    win.use
    # the begin/end will evaluate to the value returned by `yield`.
    # if an exception occurs, the window will be reset properly and
    # there will be no return value.
    begin
      yield
    ensure
      cw.use
    end
  end

  def qty                     
    with_watir_window(@win2) do  
      td(:id,'qty').text
    end
  end 
end