如何在数组中找到另一个索引数组的元素?

时间:2013-07-20 15:04:13

标签: ruby arrays indexing

我有两个数组:

["mo", "tu", "we", "th", "fr", "sa", "su"][1, 5]

根据第二个数组的索引,从第一个数组创建新数组的最短,最干净的方法是什么? 我想做这样的事情:

["mo", "tu", "we", "th", "fr", "sa", "su"][[1, 5]](不可能这样)

这会产生["tu", "sa"]

怎么可以这样做?提前谢谢!

2 个答案:

答案 0 :(得分:5)

使用Array#values_at

尝试以下操作
a = ["mo", "tu", "we", "th", "fr", "sa", "su"] 
b= [1, 5]
c = a.values_at(*b) 
# => ["tu", "sa"]

答案 1 :(得分:2)

selectwith_index可以链接以从数组中提取某些元素:

["mo", "tu", "we", "th", "fr", "sa", "su"].select.with_index {|_, index| [1, 5].include?(index)}
# => ["tu", "sa"]

以下是关于Ruby新手的答案的几点说明:

  1. 第一个块变量表示星期几(“mo”,“tu”等)并且未使用,但约定是将变量命名为“_”
  2. with_index方法可以与任何令人敬畏的Ruby迭代器链接,以获得对索引的访问权限(类似于each_with_index)。在这种情况下,没有select_with_index,因此我们使用select.with_index
相关问题