Eugene Triguba Eugene Triguba - 2 months ago 12
Ruby Question

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?

Answer

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.