将数组拆分为新数组(每个数组都有唯一的名称)

Split an array into new arrays (each with a unique name)

我正在尝试将一个数组分割成相等的大小(向下舍入)并将每个部分保存到相应的变量中。

方法each_slice成功抓取了n个大小的块。但是我想不出办法:

  1. 遍历每个块'"sub index"
  2. 为每个创建一个新数组并给每个一个唯一的名称。

    letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n"]
    
       def groups_of_five(array)
       split_array = array.each_slice(5).to_a
    
       #something like the following:
       #array(n) = Array[split_array.each {|x| x}]
    
       end 
    end
    

我希望的输出:

groups_of_five(letters)
=> array1: ["a,"b","c","d","e"]
=> array2: ["f","g","h","i","j"]
=> array3: ["k","l","m","n"]

each_slicewith_index 相结合,您将拥有所需的一切:

letters.each_slice(5).with_index(1) do |group, index| 
  puts "array#{index}: #{group.inspect}"
end

输出为:

array1: ["a", "b", "c", "d", "e"]
array2: ["f", "g", "h", "i", "j"]
array3: ["k", "l", "m", "n"]

在Ruby 1.8 以上的版本中不再可以动态设置局部变量,所以如果你想赋值给变量,它必须是实例变量或者你可以输出一个哈希。

以下将创建实例变量:

def groups_of_five(array)
  array.each_slice(5).with_index(1) do |group, index| 
    instance_variable_set "@array#{index}".to_sym, group
  end
end

groups_of_five(letters)
puts @array1 #=> ["a", "b", "c", "d", "e"]
puts @array2 #=> ["f", "g", "h", "i", "j"]
puts @array3 #=> ["k", "l", "m", "n"]

或者这将输出一个哈希:

def groups_of_five(array)
  hash = {}
  array.each_slice(5).with_index(1) do |group, index| 
    hash["array#{index}".to_sym] = group
  end
  hash
end

hash = groups_of_five(letters)
puts hash[:array1] #=> ["a", "b", "c", "d", "e"]
puts hash[:array2] #=> ["f", "g", "h", "i", "j"]
puts hash[:array3] #=> ["k", "l", "m", "n"]

如果您正在寻找从 groups_of_five(字母)到 return 的哈希结构,这里是解决方案

def groups_of_five(array)
   split_array = letters.each_slice(5).to_a
   split_array.reduce({}){ |i,a|
       index = split_array.index(a) + 1
       i["array#{index}"] = a; i
   }
end

# groups_of_five(letters)
#=> {"array1"=>["a", "b", "c", "d", "e"], "array2"=>["f", "g", "h", "i", "j"], "array3"=>["k", "l", "m", "n"]}

你可以这样做:

def group_em(a,n)
  arr = a.dup
  (1..(arr.size.to_f/n).ceil).each_with_object({}) { |i,h|
    h["array#{i}"] = arr.shift(n) }
end

group_em(letters,1)
  #=> {"array1"=>["a"], "array2"=>["b"],...,"array14"=>["n"]} 
group_em(letters,2)
  #=> {"array1"=>["a", "b"], "array2"=>["c", "d"],...,"array7"=>["m", "n"]} 
group_em(letters,5)
  #=> {"array1"=>["a", "b", "c", "d", "e"],
  #    "array2"=>["f", "g", "h", "i", "j"],
  #    "array3"=>["k", "l", "m", "n"]} 

一个变体是:

def group_em(arr,n)
  (1..(arr.size.to_f/n).ceil).zip(arr.each_slice(n).to_a)
    .each_with_object({}) { |(i,a),h| h["array#{i}"]=>a) }
end