我有两个数组:
假设学校名称数组为:[name1, name2, name3]
和slug名称为:[slug1, slug2, slug3]
。
在ruby中,我如何制作数组[[name1, slug1], [name2, slug2], [name3, slug3]]
。
我对此事的尝试有点javascript-ish
:
<% var schoolSelect = [];
for (var i=0; i<@schools.length; i++)
schoolSelect[i] = [@schools.pluck(:name)[i], @schools.pluck(:slug)[i]]; %>
答案 0 :(得分:7)
您将使用{{3}},例如:
% echo 'Voldemort' > badwords.txt
% bfg --replace-text badwords.txt myrepo.git
答案 1 :(得分:2)
建议您考虑使用该数据结构的哈希值
schools = ["first", "second", "third"]
slugs = ["a", "b", "c"]
school_slugs = {}
(0..2).each do |position|
school_slugs[schools[position]] = slugs[position]
end
# => 0..2
school_slugs
# => {"first" => "a", "second" => "b", "third" => "c"}
如果你使用Arup的方法,你也可以把它变成哈希,即
[["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]].to_h
# => {"name1"=>"slug1", "name2"=>"slug2", "name3"=>"slug3"}
答案 2 :(得分:0)
names = %w(name1 name2 name3)
slugs = %w(slug1 slug2 slug3)
每当你有两个相同大小的数组时,就像这里一样,
names.zip(slugs)
#=> [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]
和
[names, slugs].transpose
#=> [["name1", "slug1"], ["name2", "slug2"], ["name3", "slug3"]]
可以互换。