Todd Benson
12/18/2008 10:52:00 PM
On Thu, Dec 18, 2008 at 1:12 PM, Stuart Clarke
<stuart.clarke1986@gmail.com> wrote:
> Sorry I was getting to replying to you then got called off in a hurry. I
> do not understand some of the code you have used as I am relatively new
> to Ruby. Can you briefly outline the code, it would be greatly
> appreciated.
> Robert Klemme wrote earlier:
> A framework:
>
> Data = Struct.new :a, :b:, :c, :d, :e, :f
(leave off the extra : after b :-)
Struct is an automatic way to define a simple class. There, he's
defining the structure of a class that he wants to call Data with the
use of Struct. So with this statement, we will have a class that has
attributes a, b, c, d, e, f, all with getters and setters, and (at
least in 1.8.7 AFAIK) an initialize method. For example...
MySimpleClass = Struct.new :instance_var
m = MySimpleClass.new "hi"
puts m.instance_var
m.instance_var = "bye"
puts m.instance_var
#hi
#bye
>
> def Data.parse(line)
> d = new(*line.strip.split(/\s+/))
> d.f = Integer(d.f)
> d
> end
There he is defining a class method called parse on the class Data.
This method returns a Data object filled with the info that was in the
string "line".
>
> count = Hash.new 0
As explained, that was a Hash initialization with a default value of 0
>
> ARGF.each do |line|
> data = Data.parse(line)
> count[data.f[/Name:\t(.+?)\r\n/, 1]] += 1 if data.a == 100
> end
Rack up the count if the conditions are met
>
> count.each do |a, cnt|
> printf "%20s %6d\n", a, cnt
> end
Print the darn thing out!
hth,
Todd