python - Ruby 是否有类似 Python 的列表推导式?

标签 python ruby programming-languages

Python 有一个很好的特性:

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

在 Ruby 中更简单:

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

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

在 Python 中我们可以这样做:

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 中的等价物是:

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 有类似的东西吗?

最佳答案

Ruby 中常用的方式是适当的组合EnumerableArray实现相同的方法:

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

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

关于python - Ruby 是否有类似 Python 的列表推导式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319429/

相关文章:

python - Sqlite3 或 QtSql

ruby - 通过 Ruby 查询 HBase Stargate 的十六进制行键

python - 来自 stdin 用例的脚本

interop - 现代语言和 COBOL 之间是否存在互操作性障碍?

python - 根据 pandas 中另一个数据帧的相似值填充数据帧中的列

Python 将哈希值转换为数据帧

python - 分析简单的 python 脚本

ruby-on-rails - Postgres 列为列

ruby - Netbeans - 安装 SASS

c# - 从文件夹中读取图像 (OpenCV)