[英]In ruby how can i convert an array with multiple elements into a hash
您好,紅寶石新手,但到目前為止,這就是我所擁有的。
test_array = []
test_hash = {}
string = "intended key"
variable = "intended hash value"
test_array += [string,variable,true]
測試數組現在應該返回[“預期的鍵”,“預期的哈希值”,true]其他指南讓我嘗試了類似的嘗試,但收效甚微
test_hash[string] << test_array
最終,我想將更新后的數組轉換為如下所示的哈希格式
test_hash = {"intended key" => "intended hash value",true}
幫助非常感謝!
正如Ryan在評論中所提到的那樣, test_hash = {"intended key" => "intended hash value",true}
不是有效的哈希,正如您在評論中所提到的,您可能對哈希可以具有的值感到困惑。
從紅寶石文檔在這里
哈希是字典式的唯一鍵及其值的集合。 也稱為關聯數組,它們與數組相似,但是在數組使用整數作為索引的情況下,哈希允許您使用任何對象類型。
該值可以是任何對象,但是"intended hash value",true
)不是有效的對象。 你可以做
test_array = [variable,true]
test_hash[string] = test_array
puts test_hash
=> {"intended key"=>["intended hash value", true]}
但不清楚您要尋找什么。
您的哈希格式錯誤。 我不知道你到底想做什么。 但您可以使用以下示例。 我相信這會有所幫助。
string1 = "intended key"
variable1 = "intended hash value"
string2 = "boolean value"
variable2 = true
test_array1 = []
test_array2 = []
test_array1.push(string1,string2)
test_array2.push(variable1,variable2)
final_test_array = test_array1.zip(test_array2)
test_hash = Hash[final_test_array]
最終輸出:
{"intended key"=>"intended hash value", "boolean value"=>true}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.