加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用块/ proc / lambda的Ruby双管道赋值?

发布时间:2020-12-16 20:19:55 所属栏目:百科 来源:网络整理
导读:写出来真的很好 @foo ||= "bar_default" 要么 @foo ||= myobject.bar(args) 但我一直在寻找是否有办法写出类似的东西 @foo ||= do myobject.attr = new_val myobject.other_attr = other_new_val myobject.bar(args)end 在实际的功能代码中大致相当于类似的
写出来真的很好
@foo ||= "bar_default"

要么

@foo ||= myobject.bar(args)

但我一直在寻找是否有办法写出类似的东西

@foo ||= do
  myobject.attr = new_val
  myobject.other_attr = other_new_val
  myobject.bar(args)
end

在实际的功能代码中大致相当于类似的东西

@foo = if !@foo.nil?
         @foo
       else
         myobject.attr = new_val
         myobject.other_attr = other_new_val
         myobject.bar(args)
       end

我想我可以编写我自己的全局方法,如“getblock”来包装并返回任何一般的块的结果,但是我想知道是否已经有一个内置的方法来做到这一点.

解决方法

你可以使用begin..end:
@foo ||= begin
  # any statements here
end

或者考虑将块的内容分解为单独的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读