我想在ruby中使用哈希时获得默认值。查看使用获取方法的文档。所以如果没有输入散列,那么它默认为一个值。这是我的代码。如何在ruby中使用哈希获取默认值
def input_students
puts "Please enter the names and hobbies of the students plus country of birth"
puts "To finish, just hit return three times"
#create the empty array
students = []
hobbies = []
country = []
cohort = []
# Get the first name
name = gets.chomp
hobbies = gets.chomp
country = gets.chomp
cohort = gets.chomp
while !name.empty? && !hobbies.empty? && !country.empty? && cohort.fetch(:cohort, january) do #This is to do with entering twice
students << {name: name, hobbies: hobbies, country: country, cohort: cohort} #import part of the code.
puts "Now we have #{students.count} students"
# get another name from the user
name = gets.chomp
hobbies = gets.chomp
country = gets.chomp
cohort = gets.chomp
end
students
end
downvote可能是因为你还没有提出你的问题。您需要编辑问题以清楚地说明问题。 –
考虑在选择答案之前等待更长的时间(至少几个小时,也许)。快速选择可能会阻止其他答案,并将仍在解答问题的答案短路。没有急于。您仍然需要编辑您的问题,因为很多成员可能会在将来阅读您的问题(并且还会阻止更多的降低投票)。 –