这就是我正在尝试做的事情:
编写一个方法,该方法采用哈希值并在城市较大(超过 100,000)或较小(否则)时打印。打印类似的东西:温哥华是一个大城市。
这是我提供的哈希值:
bc_cities_population = {vancouver: 2135201, victoria: 316327, abbotsford: 149855, kelowna: 141767, nanaimo: 88799, white_rock: 82368, kamloops: 73472, chilliwack: 66382 }
这是我的代码:
bc_cities_population = {vancouver: 2135201, victoria: 316327, abbotsford: 149855, kelowna: 141767, nanaimo: 88799, white_rock: 82368, kamloops: 73472, chilliwack: 66382 }
bc_cities_population.each do |city, population|
if population > 100,000
puts "#{city} is a big ol city!"
elsif
puts "#{city}city is a tiny ol town"
end
end
感谢您的帮助..
编辑:这是我收到的错误。
ruby big_small_city.rb
big_small_city.rb:1: syntax error, unexpected tINTEGER, expecting keyword_do or '{' or '('
...er: 2135201, victoria: 316327, abbotsford: 149855, kelowna...
编辑2:
这是我修改后的代码,我仍然不确定为什么不起作用。
bc_cities_population = {vancouver: 2135201, victoria: 316327, abbotsford: 149855, kelowna: 141767, nanaimo: 88799, white_rock: 82368, kamloops: 73472, chilliwack: 66382 }
bc_cities_population.each do |city, population|
if population > 100_000
puts "#{city} is a big ol city!"
else
puts "#{city} is a tiny ol town"
end
end
你应该写
bc_cities_population = {vancouver: 2135201, victoria: 316327, abbotsford: 149855, kelowna: 141767, nanaimo: 88799, white_rock: 82368, kamloops: 73472, chilliwack: 66382 }
bc_cities_population.each do |city, population|
if population > 100_000
puts "#{city} is a big ol city!"
else
puts "#{city}city is a tiny ol town"
end
end
让我们运行它:
Arup-iMac:arup_ruby$ ruby test.rb
vancouver is a big ol city!
victoria is a big ol city!
abbotsford is a big ol city!
kelowna is a big ol city!
nanaimocity is a tiny ol town
white_rockcity is a tiny ol town
kamloopscity is a tiny ol town
chilliwackcity is a tiny ol town
Arup-iMac:arup_ruby$
您所做的拧干是 - if population > 100,000
- 100,000
不是计算机数字的有效表示。您可以将其写为 100000
而不是 100_000
.但是,任意数量的下划线字符 (_) 都可以出现在数字文本中的数字之间的任何位置。例如,此功能使您能够分隔数字文本中的数字组,这可以提高代码的可读性。