I’m learning ruby and have a few questions about some code I wrote for a newbie challenge. Purpose of challenge is to find country with largest population from an xml document.
I’ve included my code below. Questions I have are:
- Is there a way to avoid having to initialize the
@max_popvariable (@max_pop=0)? - Is there shorthand for combining the entire conditional block into 1 line?
- Do I have to use instance vars
@max_pop,@max_pop_country? Got error without them. - Which is more efficient:
- Loop through each country and check if
pop > max_pop(approach in code below) - Create pop hash (
pop[:country]) and then find country with highest pop
- Loop through each country and check if
- Is there hash method to return key value pair for largest element in hash (to do 4.1)?
Source Code:
@max_pop=0
doc.elements.each("cia/country") do |country|
if country.attributes["population"].to_i > @max_pop
@max_pop=country.attributes["population"].to_i
@max_pop_country=country.attributes["name"]
end
end
puts "country with largest pop is #{@max_pop_country} with pop of #{@max_pop}
I am not familiar with rexml, but you ought to be able to simplify everything to something like this:
key, value = hash.max_by{|k,v| v}.In general, if you are going to be iterating over things you should learn about Ruby’s Enumerable module. I made a reference sheet for it here.