douzi8127 2016-06-15 07:21
浏览 19

Go defer的红宝石当量是多少?

I am a new to Ruby and I am working on a project which involves using this. Go offers the defer statement, and I wanted to know how I could replicate that function in ruby.

Example:

dst, err := os.Create(dstName)
if err != nil {
    return
}
defer dst.Close()
  • 写回答

2条回答 默认 最新

  • dongma0722 2016-06-15 07:33
    关注

    There are no proper equivalents to the defer statement in ruby, however if you want to make sure that a specific code block is executed, you can use the ensure statement. The difference is that you cannot stack code blocks like defer does, but the result is the same.

    In a block

    begin
      # ...
    ensure
      # This code will be executed even if an exception is thrown
    end
    

    In a method

    def foo
      # ...
    ensure
      # ...
    end
    

    Object#ensure Marks the final, optional clause of a begin/end block, generally in cases where the block also contains a rescue clause. The code in the ensure clause is guaranteed to be executed, whether control flows to the rescue block or not.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度