Reputation: 750
Im still pretty new to programming, and i am trying to convert an array of strings into a hash with symbols. The formatting of the strings are giving me grief:
foobar = ["ABC: OPEN", "123: OPEN", "FOO: CLOSED", "BAR: CLOSED", "XYZ: OPEN", "LMO: CLOSED"]
I am trying to get this "name: status" format to transfer to a hash where the key can be a symbol:
foobar_hash = {"ABC" => :OPEN, "123" => :OPEN, "FOO" => :CLOSED, "BAR" => :CLOSED, "XYZ" => :CLOSED, "LMO" => :CLOSED}
What would be the best way to accomplish this?
Upvotes: 1
Views: 1936
Reputation: 1939
You could try this
keys = "foobar".map{|s|s.split(':')}.map(&:first)
values = "foobar".map{|s|s.split(':')}.map(&:last)
Hash[keys.zip(values)]
Upvotes: 0
Reputation: 7027
This might work :
foobar_hash = {}
foobar.each { |s| foobar_hash[s.split(":")[0].strip] = s.split(":")[1].strip.to_sym }
Upvotes: 0
Reputation: 15957
You could do something like this:
[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"}
If you need the colon
in front of the value
you can do something like this too:
[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"}
One more iteration if you need the values to be symbols, you could do this:
[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}
Upvotes: 0
Reputation: 118261
One more way :-
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}
Upvotes: 1
Reputation: 1417
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 gives you
=> {"ABC"=>:OPEN, "123"=>:OPEN, "FOO"=>:CLOSED, "BAR"=>:CLOSED, "XYZ"=>:OPEN, "LMO"=>:CLOSED}
Upvotes: 0
Reputation: 12558
Something like this?
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"}
If you want symbol key/values: Hash[arr.map { |x| x.split(": ").map(&:to_sym) }]
Upvotes: 4