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

从Ruby中的X.times返回数组的清理方式

发布时间:2020-12-16 19:48:21 所属栏目:百科 来源:网络整理
导读:我经常想对数组X执行一个动作,然后返回除该数字之外的结果.我通常写的代码如下: def other_participants output =[] NUMBER_COMPARED.times do output Participant.new(all_friends.shuffle.pop,self) end output end 有没有更清洁的方法来做到这一点? 解
我经常想对数组X执行一个动作,然后返回除该数字之外的结果.我通常写的代码如下:
def other_participants
    output =[]
    NUMBER_COMPARED.times do
      output << Participant.new(all_friends.shuffle.pop,self)
    end
    output
  end

有没有更清洁的方法来做到这一点?

解决方法

听起来像你可以使用map / collect(它们是Enumerable的同义词).它返回一个数组,内容是通过map / collect返回每次迭代.
def other_participants
  NUMBER_COMPARED.times.collect do
    Participant.new(all_friends.shuffle.pop,self)
  end
end

你不需要另外一个变量或一个明确的return语句.

http://www.ruby-doc.org/core/Enumerable.html#method-i-collect

(编辑:李大同)

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

    推荐文章
      热点阅读