From: sto.mar@... Date: 2013-07-10T00:47:52+09:00 Subject: Re: create variables depending on counter Am 09.07.2013 17:13, schrieb stefan heinrich: > As an example let us say I have an Array like this: > > Car > Dog > Car > Car > Dog > > What i want to do is I want to collect all Cars in a new Array and all > Dogs in a new Array, too. > So I need two new Arrays to do this. With Array.uniq.length I get the > number of my new Arrays I need. > Is there a way to implement this that the programme counts the uniq > elements in the array and creates variables depending on the counter. > > So difficult to explain. I hope anyone can help me. Hi, as I already said, it's not completely clear to me what you want to do. Anyway, I believe what you need is a hash :) Some use cases I could imagine: Get a list of indices for all uniq elements: array = ['Car', 'Dog', 'Dog', 'Car', 'Dog'] indices = Hash.new {|h,k| h[k] = [] } array.each_with_index {|element, index| indices[element] << index } indices # => {"Car"=>[0, 3], "Dog"=>[1, 2, 4]} indices['Car'] # => [0, 3] indices['Dog'] # => [1, 2, 4] Count the number of occurences: occurences = Hash.new(0) array.each {|element| occurences[element] += 1 } occurences # => {"Car"=>2, "Dog"=>3} Regards, Marcus --