Forum: Ruby Newbie question > count array key?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Remco S. (Guest)
on 2009-02-24 19:57
Hi,


newbie question(i guess)

a = Bookings.find(:all, :conditions => [3.days.ago])
a = [id : 1, departure : 'AMS', arrival => 'NY'],[id : 2, departure :
'AMS', arrival => 'BCN'],[id : 3, departure : 'AMS', arrival =>
'BKK'],[id : 4, departure : 'AMS', arrival => 'BKK'] ect.

The value of the key departure and arrival is dynamic based on
table(3000 combinations) and the bookings


I want to find the bookings and count the arrival and departure(s). I
the case of the code above, i want the following output.

departure = AMS > total = 5
arrival = BCN > total = 1
arrival = NY > total = 1
arrival = BKK > total = 2

How can i do this

Grtz..remco
Brian C. (Guest)
on 2009-02-25 17:46
Remco S. wrote:
> newbie question(i guess)
>
> a = Bookings.find(:all, :conditions => [3.days.ago])
> a = [id : 1, departure : 'AMS', arrival => 'NY'],[id : 2, departure :
> 'AMS', arrival => 'BCN'],[id : 3, departure : 'AMS', arrival =>
> 'BKK'],[id : 4, departure : 'AMS', arrival => 'BKK'] ect.
>
> The value of the key departure and arrival is dynamic based on
> table(3000 combinations) and the bookings
>
>
> I want to find the bookings and count the arrival and departure(s). I
> the case of the code above, i want the following output.
>
> departure = AMS > total = 5
> arrival = BCN > total = 1
> arrival = NY > total = 1
> arrival = BKK > total = 2
>
> How can i do this

You iterate through the rows, counting the values of interest.

Constructs you may find useful are:

(1) the 'each' method of the Array class (to iterate through your array)

  a.each do |booking|
    p booking
    # or do something else with it
  end

(2) Hashes, especially ones which have a default value of zero

  count = Hash.new(0)

  count["foo"] += 1
  count["bar"] += 1
  count["foo"] += 1

  # after this, count = {"foo"=>2, "bar"=>1}

(3) the 'each' method of the Hash class

  count.each do |key,value|
    puts "#{key}: #{value}"
  end

(4) The 'irb' shell, for trying these things out, or script/console if
you are using Rails (the latter will also give you full access to your
model classes)

$ irb
irb(main):001:0> count = Hash.new(0)
=> {}
irb(main):002:0> count["foo"] += 1
=> 1
irb(main):003:0> count["bar"] += 1
=> 1
irb(main):004:0> count["foo"] += 1
=> 2
irb(main):005:0> count
=> {"foo"=>2, "bar"=>1}

See your favourite Ruby documentation for more details on these topics.
If you don't have any, then an old version of the Pickaxe book is
browsable online for free here:
http://www.ruby-doc.org/docs/ProgrammingRuby/
This topic is locked and can not be replied to.