将数组分配给不同的变量

时间:2012-09-10 10:55:16

标签: ruby metaprogramming

我有一个简单的分配多个数组的要求。现在我正在做类似的事情。

   employees = Array.new
      projects = Array.new
      practices = Array.new
      entities = Array.new
      categories = Array.new
      groups = Array.new
      external_inputs = Array.new
      payrolls = Array.new

我希望employees, projects, practices, entities ...payrolls所有内容都应该在一行中分配给Array.new 请建议一些更好,更干净的方法。也许通过Metaprogramming。

4 个答案:

答案 0 :(得分:2)

employees, projects, practices, entities, categories, groups, external_inputs, payrolls = 
  8.times.map { [] }

答案 1 :(得分:2)

丑陋但满足要求:

employees, projects, practices, entities, categories, groups, external_inputs, payrolls = Array.new(8) { [] }

答案 2 :(得分:2)

  

我希望employeesprojectspracticesentities,...,payrolls所有内容都应分配到Array.new线

这里你去:

employees = Array.new; projects = Array.new; practices = Array.new; entities = Array.new; categories = Array.new; groups = Array.new; external_inputs = Array.new; payrolls = Array.new

Voilà,就像您要求的那样,单行。

现在,为什么你有一个如此庞大,复杂的方法,它需要8个局部变量是另一个问题。

答案 3 :(得分:1)

嗯,这不是一条线,但使用起来要干净得多:

employees        = []
projects         = []
practices        = []
entities         = []
categories       = []
groups           = []
external_inputs  = []
payrolls         = []

但是,如果你想“巧妙地”做到这一点,你可以尝试:

employees = projects = practices = entities = categories = groups = external_inputs = payrolls = nil
%w(employees projects practices entities categories groups external_inputs payrolls).each {|v| eval "#{v} = []" }

也就是说,将值集合到哈希中可能更容易。

Hash[*%w(employees projects practices entities categories groups external_inputs payrolls).map {|k| [k, []] }.flatten(1)]

# Result
# {"employees"=>[], "projects"=>[], "practices"=>[], "entities"=>[], "categories"=>[], "groups"=>[], "external_inputs"=>[], "payrolls"=>[]}