我想在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可能是因爲你還沒有提出你的問題。您需要編輯問題以清楚地說明問題。 –
考慮在選擇答案之前等待更長的時間(至少幾個小時,也許)。快速選擇可能會阻止其他答案,並將仍在解答問題的答案短路。沒有急於。您仍然需要編輯您的問題,因爲很多成員可能會在將來閱讀您的問題(並且還會阻止更多的降低投票)。 –