我正在為 Odin 專案解決問題。我必須對我給出的答案進行測驗,并且無法使用我制作的代碼通過測驗。我得到了正確哈希的意外結果,但由于某種原因它被包含在陣列中。
def find_favorite(array_of_hash_objects)
# take an array_of_hash_objects and return the hash which has the key/value
# pair :is_my_favorite? => true. If no hash returns the value true to the key
# :is_my_favorite? it should return nil
# array_of_hash_objects will look something like this: # [
# { name: 'Ruby', is_my_favorite?: true },
# { name: 'JavaScript', is_my_favorite?: false },
# { name: 'HTML', is_my_favorite?: false }
# ]
# TIP: there will only be a maximum of one hash in the array that will
# return true to the :is_my_favorite? key
end
我的解決方案:
array_of_hash_objects.select {|key, value| key[:is_my_favorite?] == true}
我在運行測驗后收到了這個:
`失敗/錯誤:expect(find_favorite(array)).to eq(expected_output)
expected: {:is_my_favorite?=>true, :name=>"Ruby"}
got: [{:is_my_favorite?=>true, :name=>"Ruby"}]`
我的問題是,如何從陣列中獲取回傳值?我預測我可能使用了錯誤的方法,但我認為從看到問題的人那里得到解釋可能會有所幫助。沒有谷歌搜索可以解決這個問題。這是我的第一個堆疊溢位問題。
uj5u.com熱心網友回復:
從select變為find。簡單地說,這些方法的語意是不同的:
select回傳與條件匹配的所有元素,因此是一個集合,即使它的長度為 1 或 0find回傳匹配條件的第一個元素,或者nil如果不匹配
在你的情況下,你想要find
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507580.html
標籤:红宝石
上一篇:在Ruby中使用哪一個來轉換為Number[Ruby'sBeginnersGuide]?
下一篇:js函式獲取欄位中的所有值
