你可以做這樣的事情:如果您在value
前需要colon
[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"}
你也可以做這樣的事情:
[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}
這實際上是一個體面的代碼高爾夫球問題。 – wberry 2014-11-23 18:01:06
是的。對不起,我已經適當地編輯了它 – 2014-11-23 18:15:29
'':OPEN'是否必須是字符串或符號? – Anthony 2014-11-23 18:16:28