2016-09-17 53 views
0

我想在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 
+0

downvote可能是因爲你還沒有提出你的問題。您需要編輯問題以清楚地說明問題。 –

+0

考慮在選擇答案之前等待更長的時間(至少幾個小時,也許)。快速選擇可能會阻止其他答案,並將仍在解答問題的答案短路。沒有急於。您仍然需要編輯您的問題,因爲很多成員可能會在將來閱讀您的問題(並且還會阻止更多的降低投票)。 –

回答

2

你只需要給fetch默認它可以處理。它不知道如何處理january,因爲您尚未用該名稱聲明任何變量。如果您想爲默認值設置爲字符串"january",那麼你只需要引用這樣的:

cohort.fetch(:cohort, "january") 

裏有documentation for fetch一些體面的例子。

另外,cohort不是Hash,它是String,因爲gets.chomp返回Stringfetch用於從Hash中「提取」值。你使用它的方式應該是拋出類似於:undefined method 'fetch' for "whatever text you entered":String的錯誤。

最後,由於您在條件中使用它,因此您致電fetch的結果正在評估其真實性。如果您設置了默認值,它將始終評估爲true

如果你只是想設置默認爲cohort,如果它是空的,你可以做這樣的事情:

cohort = gets.chomp 
cohort = "january" if cohort.empty? 
while !name.empty? && !hobbies.empty? && !country.empty? 
    students << { 
    name: name, 
    hobbies: hobbies, 
    country: country, 
    cohort: cohort 
    } 
    ... # do more stuff 

希望這是有幫助的。

+0

所以我快到了。剛剛必須讓一個字符串。 – AltBrian

+0

現在我得到這個錯誤'coderunner.rb:16:in input_students':未定義的方法'獲取'爲「」:String(NoMethodError)'。 – AltBrian

+0

查看我上面的擴展答案。 – dinjas

5

你有幾個選擇。 @dinjas提到了一個,可能是你想使用的那個。假設你的散列

h = { :a=>1 } 

然後

h[:a] #=> 1 
h[:b] #=> nil 

假設默認爲4。然後,隨着dinjas建議,你可以寫

h.fetch(:a, 4) #=> 1 
h.fetch(:b, 4) #=> 4 

但其他選項

h.fetch(:a) rescue 4 #=> 1 
h.fetch(:b) rescue 4 #=> 4 

h[:a] || 4 #=> 1 
h[:b] || 4 #=> 4 

你也可以創建默認進入哈希本身,用Hash#default=

h.default = 4 
h[:a] #=> 1 
h[:b] #=> 4 

或通過定義散列像這樣:

h = Hash.new(4).merge({ :a=>1 }) 
h[:a] #=> 1 
h[:b] #=> 4 

參見Hash::new

+2

也可以使用['Hash#default_proc'](http://ruby-doc.org/core-2.1.5/Hash.html#method-i-default_proc-3D)根據某些條件返回值。 – mudasobwa

+0

@mudasobwa,好點。讀者,一個常見的例子是'h.default_proc = - >(h,k){h [k] = []}',所以如果寫'h [k] << 3'並且'h'沒有鍵'k','h [k]'被設置爲等於一個空數組,然後'3'被添加到該數組。這也可以寫成'h = Hash.new {| h,k | h [k] = []} .merge()'。 –