Kalman Noel
12/16/2006 12:50:00 PM
Just Maz:
> I've got a file with a few lines:
> 1: Kevin 25 football cricket guitar
> 2: John 15 football karate
> 3: Fred 20 rugby painting
>
> Via regular expressions I'm trying to do a few things here such as
> counting how many hobbies people have and counting how many people have
> the same hobby- its this last one in particular I can't figure out.
Person = Struct.new(:name, :age, :hobbies)
data = readlines.
map { |line| line.scan(/^\d+: (\w+) (\d+) (.*?)\s*$/).flatten }.
map { |name, age, hobbies| Person.new(name, age.to_i, hobbies.split) }
# What hobbies does Kevin have?
p data.find { |p| p.name == 'Kevin' }.hobbies
# How many people like football?
p data.find_all { |p| p.hobbies.include? 'football' }.size
---
Further reading, if you use the methods above: ri Enumerable
Kalman