小编Ric*_*ick的帖子

Ruby idiom to shortcircuit使用each和map返回第一个非nil

这是我想要做的事情的本质,但"休息"不能正确地进行:

needle = nil
haystacks.each do |haystack|
  needle = haystack.look_for_needle()
  break if needle
end
Run Code Online (Sandbox Code Playgroud)

这个更短,但它会迭代每个干草堆(至少看不到),即使它不需要:

needle = nil
haystacks.each do |haystack|
  needle ||= haystack.look_for_needle()
end
Run Code Online (Sandbox Code Playgroud)

这是一个单行,但(我相信)它不是懒惰,所以它做了不必要的工作:

needle = hackstacks.map{|h| h.look_for_needle()}.detect{|x| !x.nil?}
Run Code Online (Sandbox Code Playgroud)

我觉得应该有一个班轮,但我不确定它会是:

needle = hackstacks.some_find_each_first_detect_lazy_map_thingee {|h| h.look_for_needle()}
Run Code Online (Sandbox Code Playgroud)

ruby each

6
推荐指数
2
解决办法
932
查看次数

创建带有可选嵌套内容的 freemarker 宏?

创建可以使用或不使用嵌套内容的宏的正确方法是什么?例如

<@myMacro/>
<@myMacro>my nested content</@myMacro>
Run Code Online (Sandbox Code Playgroud)

有这样的吗?或者是其他东西?

<#macro myMacro>
  <#if ??????>
    Before nested content
    <#nested/>
    After nested content
  <#else/>
    Nothing nested here
  </#if>
</#macro>
Run Code Online (Sandbox Code Playgroud)

freemarker

3
推荐指数
1
解决办法
767
查看次数

标签 统计

each ×1

freemarker ×1

ruby ×1