2

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

   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在一行中请提出一些更好更干净的方法。也许通过元编程。

4

4 回答 4

3
employees, projects, practices, entities, categories, groups, external_inputs, payrolls = 
  8.times.map { [] }
于 2012-09-10T11:06:53.960 回答
3

我想要 , employees, projects, practices, entities...,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

瞧,单行,正如你所要求的。

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

于 2012-09-10T11:34:19.463 回答
2

丑陋但满足要求:

employees, projects, practices, entities, categories, groups, external_inputs, payrolls = Array.new(8) { [] }
于 2012-09-10T11:07:39.437 回答
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"=>[]}
于 2012-09-10T11:02:17.630 回答