【问题标题】:How do I find elements in array with another indexes array?如何使用另一个索引数组查找数组中的元素?
【发布时间】:2013-07-19 18:28:38
【问题描述】:

我有两个数组:

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

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

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

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

如何做到这一点?提前致谢!

【问题讨论】:

    标签: ruby arrays indexing


    【解决方案1】:

    使用Array#values_at尝试如下操作

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

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-24
        • 2012-07-19
        • 2021-11-24
        • 2016-06-09
        • 1970-01-01
        • 1970-01-01
        • 2020-05-22
        • 2021-10-27
        相关资源
        最近更新 更多