我有一个包含字符串的数组:
["First Name", "Last Name", "Location", "Description"]
我需要将Array转换为Hash,如下所示:
{"A" => "First Name", "B" => "Last Name", "C" => "Location", "D" => "Description"}
此外,也是这样:
{"First Name" => "A", "Last Name" => "B", "Location" => "C", "Description" => "D"}
有任何想法如何处理这个最佳方式?
答案 0 :(得分:2)
您可以按照以下方式实施
def string_array_to_hash(a=[],keys=false)
headers = ("A".."Z").to_a
Hash[keys ? a.zip(headers.take(a.count)) : headers.take(a.count).zip(a)]
end
然后得到你的初始输出就是
a = ["First Name", "Last Name", "Location", "Description"]
string_array_to_hash a
#=> {"A"=>"First Name", "B"=>"Last Name", "C"=>"Location", "D"=>"Description"}
第二个输出是
a = ["First Name", "Last Name", "Location", "Description"]
string_array_to_hash a, true
#=> {"First Name"=>"A", "Last Name"=>"B", "Location"=>"C", "Description"=>"D"}
注意:只要a
小于27个对象,这将有效,否则您必须指定不同的所需输出。这是因为a)字母表只有26个字母b)哈希对象只能有唯一的键。
答案 1 :(得分:1)
你可以这样做:
arr = ["First Name", "Last Name", "Location", "Description"]
letter = Enumerator.new do |y|
l = ('A'.ord-1).chr
loop do
y.yield l=l.next
end
end
#=> #<Enumerator: #<Enumerator::Generator:0x007f9a00878fd8>:each>
h = arr.each_with_object({}) { |s,h| h[letter.next] = s }
#=> {"A"=>"First Name", "B"=>"Last Name", "C"=>"Location", "D"=>"Description"}
h.invert
#=> {"First Name"=>"A", "Last Name"=>"B", "Location"=>"C", "Description"=>"D"}
或
letter = ('A'.ord-1).chr
#=> "@"
h = arr.each_with_object({}) { |s,h| h[letter = letter.next] = s }
#=> {"A"=>"First Name", "B"=>"Last Name", "C"=>"Location", "D"=>"Description"}
使用枚举器letter
时,我们有
27.times { puts letter.next }
#=> "A"
# "B"
# ...
# "Z"
# "AA"
答案 2 :(得分:0)
如果您没有具体说明密钥名称,那么您可以试试这个
list = ["First Name", "Last Name", "Location", "Description"]
Hash[list.map.with_index{|*x|x}].invert
输出
{0=>"First Name", 1=>"Last Name", 2=>"Location", 3=>"Description"}
类似的解决方案是here。
答案 3 :(得分:0)
或..你也可以试试这个:)
letter = 'A'
arr = ["First Name", "Last Name", "Location", "Description"]
hash = {}
arr.each { |i|
hash[i] = letter
letter = letter.next
}
// => {"First Name"=>"A", "Last Name"=>"B", "Location"=>"C", "Description"=>"D"}
或
letter = 'A'
arr = ["First Name", "Last Name", "Location", "Description"]
hash = {}
arr.each { |i|
hash[letter] = i
letter = letter.next
}
// => {"A"=>"First Name", "B"=>"Last Name", "C"=>"Location", "D"=>"Description"}