【问题标题】:Match corresponding object index values from multiple arrays in Ruby匹配 Ruby 中多个数组中对应的对象索引值
【发布时间】:2013-10-31 14:24:51
【问题描述】:

我有三个数组 =

name = ["sample","test","sample"]
date = ["September","October","November"]
score = [10,20,30]

我想遍历name 中的每个对象,并返回每个等于sample 的对象的索引值。我们的想法是获取该索引并返回datescore 中的相应对象。这就是我目前的做法:

new_name_array = []
new_date_array = []
new_score_array = []
count = 0
name.each do |x|
  if x == 'sample'
    new_name_array << x
    new_date_array << date.index[count]
    new_score_aray << score.index[count]

    count += 1
  else
    count += 1
    next
  end
end

然后我有了三个新数组,其中只有我需要的值,我可以将脚本的其余部分基于这些数组。

我知道有更好的方法可以做到这一点 - 这绝不是最有效的方法。有人可以提供一些建议以更简洁的方式编写上述内容吗?

旁注:

有没有办法在循环中提取x 的整数值而不是使用count += 1

【问题讨论】:

    标签: ruby arrays loops


    【解决方案1】:

    这样的事情怎么样

    name.zip(date, score).select { |x| x.first == 'sample' }

    你会得到一个三元素数组的数组:

    [["sample", "September", 10], ["sample", "November", 30]]

    另外,如果在迭代时需要元素的索引,通常使用each_with_index

    【讨论】:

    • 我认为这实际上是我最终会使用的。非常干净,最终这将比单独的数组更容易。谢谢!
    【解决方案2】:

    这是一种方法:

    name = ["sample","test","sample"]
    date = ["September","October","November"]
    score = [10,20,30]
    
    indexes = name.map.with_index{|e,i| i if e=='sample'}.compact
    indexes # >> [0, 2]
    new_date_array = date.values_at(*indexes) # >> ["September", "November"]
    new_score_array = score.values_at(*indexes) # >> [10, 30]
    

    【讨论】:

    • 非常酷。感谢您的提示,并教我一些新方法!
    猜你喜欢
    • 2016-10-12
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多