迭代数组的更优雅方式

时间:2014-05-22 13:56:20

标签: ruby arrays ruby-on-rails-3 loops

使用以下设置:

north = [comp1]
east = [comp2, comp3, comp4, comp5, comp6]
south = [comp7, comp8]
west = [comp9, comp10, comp11]
companies = [north, east, south, west]
recruiters = ["Bob", "Bill", "Jane", "Josh"]

我想迭代companies的每个元素,并为每个元素指定一个名称。我想将招聘人员"Bob"分配给north,招聘人员"Bill"east,招聘人员"Jane"south和招聘人员{{}}的所有要素{1}}至"Josh"

一种方法是做一些事情:

west

并且将对剩余的元素重复该过程,但会更改招聘人员数组的索引。

有更优雅的方法吗?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

companies.zip(recruiters).each do |companies, recruiter| 
  companies.each {|company, recruiter| assign_recruiter(company, recruiter) }
end

我还会将companies重命名为regions

答案 1 :(得分:0)

您可以使用分配方法内联。

north.each { |c| assign_recruiter(c, recruiters[0]) }
east.each { |c| assign_recruiter(c, recruiters[1]) }
south.each { |c| assign_recruiter(c, recruiters[2]) }
west.each { |c| assign_recruiter(c, recruiters[3]) }

用这个可以访问的地方

def assign_recruiter(company, recruiter)
    c = Company.find_by(name: company)
    c.assigned_recruiter = recruiter
end

如果您不需要任何招聘人员数组,可以用字符串文字替换recruiters[x]

或者,您可以将数组放入哈希:

companies = { 
    north: [comp1]
    east: [comp2, comp3, comp4, comp5, comp6]
    south: [comp7, comp8]
    west: [comp9, comp10, comp11]
}
recruiters = {
    north: "Bob",
    east: "Bill",
    south: "Jane",
    west: "Josh"
}

然后你可以迭代哈希......

companies.each { |k, v| v.each { |c| assign_recruiter(c, recruiters[k]) } }