[英]How do I create a hash where the keys are values from an array Ruby
I have an array: 我有一个数组:
arr = [a, ab, abc]
I want to make a hash, using the values of the array as the keys: 我想使用数组的值作为键进行哈希:
newhash = [a[1], ab[1], abc[1]]
I have tried: 我努力了:
arr.each do |r|
newhash[r] == 1
end
to no avail. 无济于事。
How would I about accomplishing this in ruby? 我将如何在红宝石中实现这一目标?
== is comparison. ==是比较。 = is assigning.
=正在分配。 So just modify == into =.
因此,只需将==修改为=。 It works.
有用。
newhash = {}
arr.each do |r|
newhash[r] = 1
end
(I believe a, ab, abc are strings) (我相信a,ab,abc是字符串)
To learn more, this might help you. 要了解更多信息,这可能会对您有所帮助。 Array to Hash Ruby
数组到哈希Ruby
You can do it like this: 您可以这样做:
ary = [[:foo, 1], [:bar, 2]]
Hash[ary] # => {:foo=>1, :bar=>2}
If you want to do it like you tried earlier, you want to initialize hash correctly: 如果要像以前尝试的那样进行操作,则需要正确初始化哈希值:
ary = [:foo, :bar]
hash = {}
ary.each do |key|
hash[key] = 1
end # => {:foo=>1, :bar=>2}
If you are feeling like a one-liner, this will work as well 如果您感觉像单线纸一样,也可以
h = Hash[arr.collect { |v| [v, 1] } ]
collect
is invoked once per element in the array, so it returns an array of 2-element arrays of key-value pairs. 数组中的每个元素都调用一次一次
collect
,因此它返回键值对的2元素数组。
Then this is fed to the hash constructor, which turns the array of pairs into a hash 然后将其馈送到哈希构造函数,该哈希构造函数将成对的数组转换为哈希
You could also use the #reduce
method from Enumerable
(which is included into the Array
class). 您还可以使用
Enumerable
的#reduce
方法(包含在Array
类中)。
new_hash = arr.reduce({}) { |hsh, elem| hsh[elem] = 1; hsh }
And your new_hash
looks like this in Ruby: 而您的
new_hash
在Ruby中如下所示:
{"a": 1, "ab": 1, "abc": 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.