【问题标题】:Entire hash getting returned at the end of the loop在循环结束时返回整个哈希
【发布时间】:2016-09-30 00:18:22
【问题描述】:

代码

$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

问题

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

【问题讨论】:

  • 只需使用map 而不是each。请参阅文档。
  • 您可以删除format_cities并添加puts $dail_book.keys.map { |citie| citie.split('_').map(&:capitalize).join(' ') }.sort

标签: ruby


【解决方案1】:

each 方法返回它被调用的原始可枚举对象,这就是为什么你在循环结束后保持putsing 整个散列。

【讨论】:

    【解决方案2】:

    您在代码中调用了两次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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2019-03-25
      • 1970-01-01
      • 2012-03-05
      • 2014-11-14
      相关资源
      最近更新 更多