Eugene Triguba
Eugene Triguba

Reputation: 82

Entire hash getting returned at the end of the loop

Code

$dail_book = { 
  "los_angeles" => 212,
  "new_york" => 523,
  "portland" => 234,
  "seattle" => 502,
  "miami" => 910,
  "san_francisco" => 345,
  "sioux_falls" => 543,
  "omaha" => 642,
  "minneapolis" => 342,
  "san_diego" => 233
}

# Removes the underscore, captalizes each city,
# and prints it back to the user
def format_cities(k)
  puts "#{k.split('_').map(&:capitalize).join(' ')}"
end


# Loops through $dail_book
def display_cities
  puts "Options: "
  puts $dail_book.sort.each {|k,v| format_cities(k)}
end

Output

Options: 
Los Angeles
Miami
Minneapolis
New York
Omaha
Portland
San Diego
San Francisco
Seattle
Sioux Falls
los_angeles
212
miami
910
minneapolis
342
new_york
523
omaha
642
portland
234
san_diego
233
san_francisco
345
seattle
502
sioux_falls
543

Question

Why does the entire hash get returned at the end of the loop? What's happening?

Upvotes: 0

Views: 62

Answers (2)

Stefan
Stefan

Reputation: 114158

You are calling puts twice in your code:

def format_cities(k)
  puts ...         # <- here
end

def display_cities
  # ...
  puts $dail_bo... # <- and here
end

Try to keep your methods focused and modular. display_cities obviously displays something, so puts is expected here. format_cities on the other hand converts a value. It should not print anything.

Futhermore, its name (..._cities, plural) suggest that it is formatting multiple cities at once, whereas it only formats one city at a time. It should therefore be called format_city (singular):

# removes the underscore, capitalizes each word
def format_city(city)
  city.split('_').map(&:capitalize).join(' ')
end

Then, move the printing part into the display related method. But instead of printing the result of each (which returns the collection), move puts into the loop to print each formatted city name:

def display_cities
  puts "Options: "
  $dail_book.sort.each { |k, v| puts format_city(k) }
end

Upvotes: 1

izaban
izaban

Reputation: 1023

The each method returns the original enumerable object it was called upon, this is why you keep putsing the entire hash after the end of the loop.

Upvotes: 1

Related Questions