Hi --

On Wed, 20 Aug 2008, Adam Akhtar wrote:

> I making a script which generates some basic stats for completed
> listings on ebay. Its merely a means to improve on my ruby so its pretty
> primitive ;)
>
> I have an array of hashes. Each hash represents a listing on ebay.
> e.g.
> {:title => "Canon Accessory R45-WD45", :model_number =>"R45-WD45"
> :did_it_sell => TRUE}
>
> Within in the array there will be many listings for the same product.
> E.g. 25 wiis, 45 xboxes 35 sigma 18-50mm lenses etc.
>
> I want to work out statistics for each product grouping. Teh desired
> output would be something like this
>
> Wii    - Total listings 25. Total sold 10. Sell through rate 40%
> Xbox   - Total listings 50. Total sold 2. Sell through rate  4%
>
> So i need to at least sort the array of products in order of their model
> number passing sort a custom block.
>
>> From here on im not sure how to proceed. Should I bundle the groupings
> of model numbers into their own arrays or should i simply iterate over
> this nicely sorted array and make the script keep a mental note of what
> product its calculating for.
>
> in C i would have used a structure to contain the product information.
> Is a hash the best thing to use?

You could probably generate a report fairly easily in this case with
hash and array manipulation, but in general, in cases where you'd be
likely to create a structure in C, in Ruby you'd typically write a
class that has the attributes and methods you need. So maybe something
like this:

class Item
   attr_reader :title, :model_number, :sold

   def initialize(hash)
     @title, @model_number, @sold = hash.values_at(:title,
                              :model_number, :did_it_sell)
   end

   def <=>(other)
     model_number <=> other.model_number
   end
end

and then if you have an array of hashes you can turn it into an array
of items:

   items = hashes.map {|h| Item.new(h) }

and then items.sort will be sorted by model number (because of the <=>
definition in Item).


David

-- 
Rails training from David A. Black and Ruby Power and Light:
   Advancing With Rails    August 18-21    Edison, NJ          *
   Intro to Ruby on Rails  January 12-15   Fort Lauderdale, FL
   Advancing with Rails    January 19-22   Fort Lauderdale, FL
* Co-taught by D.A. Black and Erik Kastner
See http://www.rubypal.com for details and updates!