在循环结束时返回整个哈希

时间:2016-09-29 15:17:45

标签: ruby

代码

$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

输出

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

问题

为什么在循环结束时返回整个哈希?发生了什么?

2 个答案:

答案 0 :(得分:1)

每个方法返回它被调用的原始可枚举对象,这就是你在循环结束后保留​​puts整个哈希的原因。

答案 1 :(得分:1)

您在代码中呼叫puts两次:

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

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

尽量保持您的方法集中和模块化。 display_cities显然显示某些内容,因此此处需要puts。另一方面,format_cities转换一个值。它不应该打印任何东西。

此外,它的名称(..._cities,复数)表明它一次格式化多个城市,而它一次只格式化一个城市。因此,它应该被称为format_city(单数):

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

然后,将打印部件移动到与显示相关的方法中。但是,不是打印each(返回集合)的结果,而是将puts 移动到循环中以打印每个格式化的城市名称:

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