gpt4 book ai didi

Ruby 惯用法短路返回第一个非零使用每个和映射

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

这是我正在尝试做的事情的本质,但“中断”不正确:

needle = nil
haystacks.each do |haystack|
needle = haystack.look_for_needle()
break if needle
end

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

needle = nil
haystacks.each do |haystack|
needle ||= haystack.look_for_needle()
end

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

needle = hackstacks.map{|h| h.look_for_needle()}.detect{|x| !x.nil?}

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

needle = hackstacks.some_find_each_first_detect_lazy_map_thingee {|h| h.look_for_needle()}

最佳答案

使用 Ruby 2.x lazy enumerators :

needle = haystacks.lazy.map(&:look_for_needle).reject(&:nil?).first

或者:

needle = haystacks.lazy.map(&:look_for_needle).detect(&:itself)

或者(@DavidMoles):

needle = haystacks.lazy.filter_map(&:look_for_needle).first

关于Ruby 惯用法短路返回第一个非零使用每个和映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214344/

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