繁体   English   中英

将Ruby数组转换为带符号的哈希

[英]Converting ruby array into a hash with symbols

我还是编程新手,我正在尝试将字符串数组转换为带符号的哈希。 字符串的格式让我感到悲伤:

foobar = ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]

我正在尝试获取这种“名称:状态”格式,以转移到其中键可以是符号的哈希值:

foobar_hash = {"ABC" => :OPEN, "123" => :OPEN, "FOO" => :CLOSED, "BAR" => :CLOSED, "XYZ" => :CLOSED, "LMO" => :CLOSED}

做到这一点的最佳方法是什么?

像这样吗

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) }] Hash[arr.map { |x| x.split(": ").map(&:to_sym) }]

另一种方法:

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}

您可以执行以下操作:

[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"}

如果您需要在value前面加上colon ,也可以执行以下操作:

[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}

这可能有效:

foobar_hash = {}
foobar.each { |s| foobar_hash[s.split(":")[0].strip] = s.split(":")[1].strip.to_sym }
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}

你可以试试这个

keys = "foobar".map{|s|s.split(':')}.map(&:first)
values = "foobar".map{|s|s.split(':')}.map(&:last)

Hash[keys.zip(values)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM