Ruby基于传递给方法的可变数量的参数创建数组

时间:2014-08-06 19:32:03

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个方法,我想传递一些参数,然后根据传入的参数创建一些数组。

def method(*args)
  number_of_arrays = args.count
  for i in 1..number_of_args
    # create arrays
  end
  args.map do |arg|
      # do something and add to an array
  end
  # I should now have a number of different arrays based on how many arguments are passed in
  # do something with those arrays
end

任何指导?

1 个答案:

答案 0 :(得分:2)

def method(*args)
  arrays = Array.new(args.count) { [] }

  args.each_with_index do |arg, index|
      arrays[index] << # add some form of the arg to each array
  end
end