首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >我如何突破地图/收集并返回到那个点之前收集到的任何东西?

我如何突破地图/收集并返回到那个点之前收集到的任何东西?
EN

Stack Overflow用户
提问于 2011-07-13 00:56:25
回答 5查看 14.6K关注 0票数 28

我正在用代码重写这个问题:

代码语言:javascript
复制
many = 1000

# An expensive method.
#
# It returns some data or nil if no result is available.
expensive_method = lambda do
  rand(5) == 0 ? nil : "foo"
end

# Now, let's collect some data and stop collecting when no more data is
# available.

# This is concise but doesn't work.
collection = many.times.map do
  expensive_method.call || break
end

puts collection.is_a? Array # false

# This is less concise but works.
collection = []
many.times do
  collection << (expensive_method.call || break)
end

puts collection.is_a? Array # true

# My inner Rubyist ponders: Is it possible to accomplish this more concisely
# using map?
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6668008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档