在将输入添加到数组时遇到问题

时间:2019-03-19 17:28:01

标签: arrays ruby

我有一个问题,我想让我让用户将输入输入到数组中。我很难理解这一点,将不胜感激。

问题如下:

设计一个程序,使用户可以将12个月中的每个月的总降雨量输入数组。该程序应计算并显示当年的总降雨量,平均每月降雨量以及降雨量最高和最低的月份。

这是我到目前为止所写的内容:

def get_rainfall(a, b)
  rain_array = []
  rain_array.push(a => b)
  puts rain_array
end

get_rainfall('january', 300)

2 个答案:

答案 0 :(得分:1)

感谢更新问题C_B。

我认为您在这里遇到的小问题是在散列和数组之间。

您当前的方法会产生以下结果:

#=> [{"january"=>300}, {"february"=>...}]

之所以会发生这种情况,是因为调用rain_array.push(a => b)时,每次都会在a => b中将哈希值推送到数组中。

在我看来,您最好将整个内容存储为散列,也许:

hash = {}

def get_rainfall(hash, key, value)
  hash[key] = value
  puts hash
end

get_rainfall(hash, 'january', 300)
# {"january"=>300}

get_rainfall(hash, 'february', 200)
#{"january"=>300, "february"=>200}

您添加了更多的哈希,它们将以月为键存储,以降雨量为值。

或者,您也可以推送一个数组数组-调整当前方法:

rain_array = []

def get_rainfall(array, a, b)
  array.push([a, b])
  puts array
end

get_rainfall(rain_array, 'january', 300)
# january
# 300

get_rainfall(rain_array, 'february', 200)
# january
# 300
# february
# 200

您会注意到我正在提取数组或哈希的声明以将值存储在方法之外;如果没有此操作,则该方法运行后将立即失去对它的访问权限。

希望有帮助-如果您有任何疑问或疑问,欢迎扩展。让我知道你过得怎么样。


基于关于获取用户输入的进一步评论的又一个更新。尝试以下操作以开始使用:

hash = {}

def get_rainfall(hash, month)
  puts "Please enter value for #{month}"
  hash[month] = gets.chomp
  puts hash
end


get_rainfall(hash, 'january')

答案 1 :(得分:0)

我将以简单的脚本形式写我的答案,以免使这里的要求过于复杂。

最小的方法是暂时不用担心月份名称,只需收集一个包含12个值的列表(数组)即可进行计算。

rainfall = 1.upto(12).map do |month_nr|

  # `print` and `puts` are practically the same with the only difference being
  # that `puts` adds a newline character to the string if it doesn't have one

  # output the question to the user
  print "enter the rainfall for month #{month_nr}: "
  # get the input from the user and convert it into an integer
  gets.to_i # output the rainfall
end

puts "the total rainfall is: #{rainfall.sum}"
puts "the average rainfall is: #{rainfall.sum / rainfall.size}"
puts "the highest rainfall is: #{rainfall.max}"
puts "the lowest rainfall is: #{rainfall.min}"

如果您关心月份名称,可以执行以下操作:

# create an array of all months
months = %w[January February March April May June July August September October November December]
# ask the user for each moth the amount of rainfall
rainfall = months.map do |month_name|
  print "enter the rainfall for month #{month_name}: "
  [month_name, gets.to_i] # output both the month name and the rainfall provided
end

# convert [['January', 123], ['February', 456], ...]
# to { 'January' => 123, 'February' => 456, ... }
rainfall = rainfall.to_h

puts "the total rainfall is: #{rainfall.values.sum}"
puts "the average rainfall is: #{rainfall.values.sum / rainfall.size}"
# search the key with the highest value
puts "the month with the highest rainfall is: #{rainfall.key(rainfall.values.max)}"
# search the key with the lowest value
puts "the month with the lowest rainfall is: #{rainfall.key(rainfall.values.min)}"

如果不清楚,请参阅您遇到困难的事物的参考。如果还是不清楚,请在评论中提问。

引用: