루비를 가장 잘 활용하는 5가지 예
루비로 무엇을 할 수 있는지 궁금한 적이 있으신가요? 글쎄요, 아마도 하늘이 한계일 것입니다만, 어느 정도 알려진 몇 가지 사례에 대해 이야기하게 되어 기쁩니다...
Read an article coming from our Ruby Expert and learn why you don’t need to always youse hash.
When we want to aggregate some stuff, very often we use #each_with_object
or extend the regular loop 사용 #with_object
. But in most cases 루비 개발자 are using a plain hash as the aggregator and maybe it’s fine, but in this article, I’d like to show you that it doesn’t always have to be a hash.
We assume that all the files are placed in one directory (people
).
Let’s say we have the following people/people.csv
file:
First Name,Last Name,Age
John,Doe,24
Jane,Dee,45
Josh,Bee,55
Andrea,Boya,34
Andrew,Moore,54
We want to find the total of rows and the average age – we could write the following script:
people/parser.rb
require 'csv'
aggregated = CSV.foreach('people.csv', headers: true)
.withobject({ total: 0, totalage: 0 }) do |row, agg|
agg[:total] += 1
agg[:totalage] += row['Age'].toi
end
total = aggregated[:total]
averageage = aggregated[:totalage].to_f / total
puts "Total: #{total}"
puts "Average age: #{average_age}"
And yes, it does the thing but reading such a 코드 is a doubtful pleasure. It feels like a too low level. We can improve it by providing a dedicated aggregator for the loop.
people/age_aggregator.rb
class AgeAggregator
attrreader :total, :totalage
def initialize
@total = 0
@total_age = 0
end
def increment!
@total += 1
end
def incrementage!(age)
@totalage += age
end
def averageage
totalage.to_f / total
end
end
And then our loop would look as below:
people/parser.rb
require 'csv'
requirerelative './ageaggregator.rb'
aggregated = CSV.foreach('people.csv', headers: true)
.withobject(AgeAggregator.new) do |row, agg|
agg.increment!
agg.incrementage!(row['Age'].to_i)
end
puts "Total: #{aggregated.total}"
puts "Average age: #{aggregated.average_age}"
I think it’s much clearer.
We’ve written more code, but our lower-level details are extracted to the separate class. Now the main script reads much better.
Of course, you can argue that the example is too simple to put so much effort into refactoring, but c’mon – it’s just an example ;). If you had to aggregate more data, such aggregator objects are really the way to rescue.
자세히 읽어보세요: