ruby-on-rails - 如何从Ruby中的单词数组中获取所有对角线?
问题描述
我在 Ruby 中有一个数组
words = ["horses", "follow", "useful", "offset"]
参考:
h o r s e s
f o l l o w
u s e f u l
o f f s e t
我想得到一个像这样的所有对角线的列表。这是我期望的结果:
["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]
如果有人能在这方面对我有所帮助,那将会很有帮助。谢谢
解决方案
试试看:
words = ["horses", "follow", "useful", "offset"]
words.reverse.each_with_index.map{|s,i| " " * i + s }.inject(Array.new(words.size + words.last.size-1,"")) do |a,s|
s.chars.each_with_index do |c,i|
a[i] = c + a[i]
end
a
end.map(&:strip)
# => ["o", "uf", "fsf", "hoes", "olfe", "rlut", "sol", "ew", "s"]
首先words.reverse.each_with_index.map{|s,i| " " * i + s }
构建带有空白偏移量的数组:
offset
useful
follow
horses
注入创建空字符串数组,并在主块内将每个字符串字符添加到正确的数组元素
推荐阅读
- node.js - 为什么使用完整路径访问命令与仅通过命令名称不同?
- regex - 低于 250 美元的正则表达式
- python - selenium.common.exceptions.WebDriverException:unknown error:cannot connect to chrome at 127.0.0.1:9222 from unknownerror:unable to discover open pages
- python - pyFLTK 菜单栏中是否可以有图标?
- prometheus - 如何让客户端应用程序事件进入普罗米修斯
- python - 准备 HDF5 数据以创建 scikit ML 模型
- javascript - 为什么 Express Session 变量 (userID) 不在浏览器中创建 cookie?
- python - 如何在大于和小于端点的python中绘制分箱数据
- r - 使用 R 列出 https 服务器上的文件
- ruby - 带有多个参数的 Ruby 重载运算符