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

ruby – 何时使用隐式或显式代码块

发布时间:2020-12-16 23:20:02 所属栏目:百科 来源:网络整理
导读:我试图了解何时应该隐式或显式地编码块.给出以下代码块: 隐含 def two_times_implicit return "No block" unless block_given? yield yield endputs two_times_implicit { print "Hello "}puts two_times_implicit 明确 def two_times_explicit (i_am_a_blo
我试图了解何时应该隐式或显式地编码块.给出以下代码块:

>隐含

def two_times_implicit 
  return "No block" unless block_given? 
  yield 
  yield 
end

puts two_times_implicit { print "Hello "}
puts two_times_implicit

>明确

def two_times_explicit (&i_am_a_block) 
  return "No block" if i_am_a_block.nil? 
  i_am_a_block.call 
  i_am_a_block.call 
end 

puts two_times_explicit { puts "Hello"}
puts two_times_explicit

是否更喜欢使用一个而不是另一个?是否存在一种标准做法,是否存在一种情况,即哪种情况比另一种情况更好或不同,哪种情况根本不起作用?

解决方法

通过&接收块从块中创建一个新的proc对象,因此从效率的角度来看,最好不要使用它.但是,使用&通常可以更容易地定义可能会或可能不会占用块的方法,并且使用&,您也可以将块与参数一起处理,因此它是许多人的首选.

(编辑:李大同)

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

    推荐文章
      热点阅读