[英]Match corresponding object index values from multiple arrays in Ruby
I have three arrays = 我有三个数组=
name = ["sample","test","sample"]
date = ["September","October","November"]
score = [10,20,30]
I want to loop through each object in name
and return the index value of every object that is equal to sample
. 我想循环遍历每个对象的name
并返回每个等于sample
对象的索引值。 The idea is to then take that index and return the corresponding objects in date
and score
. 然后的想法是获取该索引并返回date
和score
的相应对象。 This is how I'm doing it currently: 这就是我目前正在做的事情:
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
Then I have three new arrays that have only the values I need, and I can base the rest of my script off of those arrays. 然后我有三个新的数组,只有我需要的值,我可以将我的脚本的其余部分基于这些数组。
I know there's a better way to do this - There's no way this is the most efficient way. 我知道有更好的方法可以做到-这是最有效的方法。 Can someone provide some suggestions to write the above in a cleaner way? 有人可以提供一些建议,以更清洁的方式写上述内容吗?
Sidenote: 边注:
Is there a way to pull the integer value for x
in the loop instead of using the count += 1
? 有没有办法在循环中提取x
的整数值,而不是使用count += 1
?
How about something like 怎么样的
name.zip(date, score).select { |x| x.first == 'sample' }
You'll get back an array of three-element arrays: 你将得到一个三元素数组的数组:
[["sample", "September", 10], ["sample", "November", 30]]
Also, if you need the index of an element when you're iterating, you usually use each_with_index
. 此外,如果在迭代时需要元素的索引,通常使用each_with_index
。
Here is one way : 这是一种方式:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.