On Wed, Jul 10, 2013 at 7:14 AM, <sto.mar / web.de> wrote:

> Am 10.07.2013 00:03, schrieb stefan heinrich:
>
>  can u say how I have to use the Hash with the headers. I have tried
>> everything but it doesn't work.
>>
>
> That's not a very useful information...
>
>
> You can take my first example:
>
> Am 09.07.2013 17:47, schrieb sto.mar / web.de:
>
>  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]
>>>
>>
> assuming your data is given as a 2-dimensional array:
>
> data = [
>   ['Dog', 12],
>   ['Car', 14],
>   ['Car', 67],
>   ['Dog', 98],
>   ['Dog', 32]
> ]
>
> then this would work (first, I create a hash with [] as the
> default value, that's the trickiest part of the whole thing):
>
> values = Hash.new {|h,k| h[k] = [] }
> data.each {|header, value| values[header] << value }
>

You can also use Enumerable#group_by:

irb(main):008:0> data.group_by {|s,i| s}
=> {"Dog"=>[["Dog", 12], ["Dog", 98], ["Dog", 32]], "Car"=>[["Car", 14],
["Car", 67]]}
irb(main):009:0> data.group_by {|s,i| s}.each {|k,v| v.map! {|s,i| i}}
=> {"Dog"=>[12, 98, 32], "Car"=>[14, 67]}


> Depending on how your data is given, you need to modify
> the second line.
>

I was going to ask in what structure the data is available.  That bit of
information seems to be missing from the discussion.

I suggest you also look into the docs for the Hash class and
> make heavy use of irb.


That's excellent advice.

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/