我仍然是编程的新手,我正在尝试将字符串数组转换为带符号的哈希。字符串的格式化让我感到悲伤:
foobar = ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]
我正在尝试将此“name:status”格式转换为哈希,其中键可以是符号:
foobar_hash = {"ABC" => :OPEN, "123" => :OPEN, "FOO" => :CLOSED, "BAR" => :CLOSED, "XYZ" => :CLOSED, "LMO" => :CLOSED}
实现这一目标的最佳方法是什么?
答案 0 :(得分:4)
这样的东西?
arr = [
"ABC: OPEN",
"123: OPEN",
"FOO: CLOSED",
"BAR: CLOSED",
"XYZ: OPEN",
"LMO: CLOSED"
]
Hash[arr.map { |x| x.split ": " }]
=> {"ABC"=>"OPEN",
"123"=>"OPEN",
"FOO"=>"CLOSED",
"BAR"=>"CLOSED",
"XYZ"=>"OPEN",
"LMO"=>"CLOSED"}
如果您需要符号键/值:Hash[arr.map { |x| x.split(": ").map(&:to_sym) }]
答案 1 :(得分:1)
还有一种方法: -
arr = [
"ABC: OPEN",
"123: OPEN",
"FOO: CLOSED",
"BAR: CLOSED",
"XYZ: OPEN",
"LMO: CLOSED"
]
arr.each_with_object({}) do |string, hash|
key, val = string.scan(/\w+/)
hash[key] = val.to_sym
end
# => {"ABC"=>:OPEN,
# "123"=>:OPEN,
# "FOO"=>:CLOSED,
# "BAR"=>:CLOSED,
# "XYZ"=>:OPEN,
# "LMO"=>:CLOSED}
答案 2 :(得分:0)
你可以这样做:
[4] pry(main)> foobar = ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]
=> ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]
[5] pry(main)> foobar.map { |i| i.split(": ") }.to_h
=> {"ABC"=>"OPEN",
"123"=>"OPEN",
"FOO"=>"CLOSED",
"BAR"=>"CLOSED",
"XYZ"=>"OPEN",
"LMO"=>"CLOSED"}
如果您需要colon
前面的value
,您也可以这样做:
[14] pry(main)> foobar.map { |i| i.gsub(": ", " :") }.map { |j| j.split(" ") }.to_h
=> {"ABC"=>":OPEN",
"123"=>":OPEN",
"FOO"=>":CLOSED",
"BAR"=>":CLOSED",
"XYZ"=>":OPEN",
"LMO"=>":CLOSED"}
如果您需要将值作为符号,可以再做一次迭代,您可以这样做:
[35] pry(main)> foobar.map { |i| i.split(": ") }.each_with_object({}) do |array, hash|
[35] pry(main)* hash[array.first] = array.last.to_sym
[35] pry(main)* end
=> {"ABC"=>:OPEN, "123"=>:OPEN, "FOO"=>:CLOSED, "BAR"=>:CLOSED, "XYZ"=>:OPEN, "LMO"=>:CLOSED}
答案 3 :(得分:0)
这可能有效:
foobar_hash = {}
foobar.each { |s| foobar_hash[s.split(":")[0].strip] = s.split(":")[1].strip.to_sym }
答案 4 :(得分:0)
foobar = ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]
foo_hash = Hash.new
foobar.each { |str| k,v = str.split(': '); foo_hash[k] = v.to_sym }
foo_hash给你
=> {"ABC"=>:OPEN, "123"=>:OPEN, "FOO"=>:CLOSED, "BAR"=>:CLOSED, "XYZ"=>:OPEN, "LMO"=>:CLOSED}
答案 5 :(得分:0)
你可以试试这个
keys = "foobar".map{|s|s.split(':')}.map(&:first)
values = "foobar".map{|s|s.split(':')}.map(&:last)
Hash[keys.zip(values)]