Ruby中的列表理解 [英] List comprehension in Ruby

查看:321
本文介绍了Ruby中的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要执行与Python列表推导相同的操作,请执行以下操作:

To do the equivalent of Python list comprehensions, I'm doing the following:

some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}

是否有更好的方法……也许只用一个方法调用?

Is there a better way to do this...perhaps with one method call?

推荐答案

如果确实愿意,可以创建一个Array#comprehend方法,如下所示:

If you really want to, you can create an Array#comprehend method like this:

class Array
  def comprehend(&block)
    return self if block.nil?
    self.collect(&block).compact
  end
end

some_array = [1, 2, 3, 4, 5, 6]
new_array = some_array.comprehend {|x| x * 3 if x % 2 == 0}
puts new_array

打印:

6
12
18

我可能会按照您的方式做.

I would probably just do it the way you did though.

这篇关于Ruby中的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆