在ruby中,我如何将具有多个元素的数组转换为哈希

时间:2016-09-03 02:38:11

标签: ruby

你好ruby的新手,但到目前为止,这就是我所拥有的。

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}

非常感谢!

2 个答案:

答案 0 :(得分:1)

正如Ryan在评论中提到的那样,test_hash = {"intended key" => "intended hash value",true}不是有效的哈希值,正如您在评论中提到的,您可能会对哈希值可能具有的值感到困惑。

来自ruby doc here

  

Hash是一个类似字典的唯一键及其组合的集合   值。也称为关联数组,它们类似于数组,   但是在Array使用整数作为索引的情况下,Hash允许你使用   使用任何对象类型。

值可以是任何对象,但"intended hash value",true不是有效对象。你可以做到

test_array = [variable,true]
test_hash[string] = test_array

puts test_hash  
=> {"intended key"=>["intended hash value", true]}

但目前尚不清楚你在寻找什么。

答案 1 :(得分:0)

您的哈希格式错误。我不知道你想要做什么。但你可以使用下面的例子。我相信这会有所帮助。

method

最终输出:

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]