Ruby 有类似 Python 的列表推导式吗? [英] Does Ruby have something like Python's list comprehensions?

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

问题描述

Python 有一个很好的特性:

Python has a nice feature:

print([j**2 for j in [2, 3, 4, 5]]) # => [4, 9, 16, 25]

在 Ruby 中它更简单:

In Ruby it's even simpler:

puts [2, 3, 4, 5].map{|j| j**2}

但如果是关于嵌套循环,Python 看起来更方便.

but if it's about nested loops Python looks more convenient.

在 Python 中我们可以这样做:

In Python we can do this:

digits = [1, 2, 3]
chars = ['a', 'b', 'c']    
print([str(d)+ch for d in digits for ch in chars if d >= 2 if ch == 'a'])    
# => ['2a', '3a']

Ruby 中的等价物是:

The equivalent in Ruby is:

digits = [1, 2, 3]
chars = ['a', 'b', 'c']
list = []
digits.each do |d|
    chars.each do |ch|
        list.push d.to_s << ch if d >= 2 && ch == 'a'
    end
end
puts list

Ruby 有类似的东西吗?

Does Ruby have something similar?

推荐答案

Ruby 中常用的方式是将 EnumerableArray 方法实现相同:

The common way in Ruby is to properly combine Enumerable and Array methods to achieve the same:

digits.product(chars).select{ |d, ch| d >= 2 && ch == 'a' }.map(&:join)

这仅比列表推导式长 4 个左右的字符,并且同样具有表现力(恕我直言,当然,但由于列表推导式只是列表 monad 的一种特殊应用,有人可能会争辩说,使用Ruby 的集合方法),同时不需要任何特殊的语法.

This is only 4 or so characters longer than the list comprehension and just as expressive (IMHO of course, but since list comprehensions are just a special application of the list monad, one could argue that it's probably possible to adequately rebuild that using Ruby's collection methods), while not needing any special syntax.

这篇关于Ruby 有类似 Python 的列表推导式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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