說我有陣列a = ["a","b"]
而HashMap的{"hello" => "world", "a" => "d"}
檢查是否一個HashMap鍵陣列中的全部
,將返回錯誤的陣列「A」,因爲「你好」不是。
散列圖:{"a" => "hello", "a" => "world"}
沒問題。
有沒有辦法做到這一點,而無需手動做所有的工作?例如:查找hashmap鍵是否是數組的子集?
說我有陣列a = ["a","b"]
而HashMap的{"hello" => "world", "a" => "d"}
檢查是否一個HashMap鍵陣列中的全部
,將返回錯誤的陣列「A」,因爲「你好」不是。
散列圖:{"a" => "hello", "a" => "world"}
沒問題。
有沒有辦法做到這一點,而無需手動做所有的工作?例如:查找hashmap鍵是否是數組的子集?
這將工作:
(hash.keys - a).empty?
# if returns true means all keys present in array.
# if returns false means all keys are not present in array.
嘗試是這樣的:
keys = hashmap.keys
(keys - a).empty?
是結果 '鍵 - 一個' 是空的 - 它意味着所有的按鍵都排列
是你在找這個
a = ["a","b"]
b = {"hello" => "world", "a" => "d"}
(a-b.keys).empty?
你應該將對象'{「hello」=>「world」,「a」=>「d」}作爲「散列」(即「Hash」的實例)。 「散列表」(又名「散列表」)是指數據結構。 –
'{「a」=>「hello」,「a」=>「world」}'不是很好,因爲哈希不能有重複的鍵。 :-)你也可以寫'hash.values_at(* a).size == hash.size',但是')hash.keys-a).empty?'更清晰。 –