【发布时间】:2013-10-31 14:24:51
【问题描述】:
我有三个数组 =
name = ["sample","test","sample"]
date = ["September","October","November"]
score = [10,20,30]
我想遍历name 中的每个对象,并返回每个等于sample 的对象的索引值。我们的想法是获取该索引并返回date 和score 中的相应对象。这就是我目前的做法:
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?
【问题讨论】: