gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:55 25 4
gpt4 key购买 nike

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 并在最后声明它看起来很难看。是否有更简洁的方法返回值?

最佳答案

只需返回 block 中的内部值。还要确保如果发生异常,您将保持一致的状态:

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

关于ruby - 这个代码片段有更好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com