craig
craig

Reputation: 26262

Serialize an array of hashes

I have an array of hashes:

  records = [
    {
      ID: 'BOATY',
      Name: 'McBoatface, Boaty'
    },
    {
      ID: 'TRAINY',
      Name: 'McTrainface, Trainy'
    }
  ]

I'm trying to combine them into an array of strings:

["ID,BOATY","Name,McBoatface, Boaty","ID,TRAINY","Name,McTrainface, Trainy"]

This doesn't seem to do anything:

irb> records.collect{|r| r.each{|k,v| "\"#{k},#{v}\"" }}
#=> [{:ID=>"BOATY", :Name=>"McBoatface, Boaty"}, {:ID=>"TRAINY", :Name=>"McTrainface, Trainy"}]

** edit **

Formatting (i.e. ["Key0,Value0","Key1,Value1",...] is required to match a vendor's interface.

** /edit **

What am I missing?

Upvotes: 1

Views: 129

Answers (4)

Nondv
Nondv

Reputation: 819

You sure you wanna do it this way?

Check out Marshal. Or JSON.

You could even do it this stupid way using Hash#inspect and eval:

serialized_hashes = records.map(&:inspect) # ["{ID: 'Boaty'...", ...]
unserialized = serialized_hashes.map { |s| eval(s) }

Upvotes: 0

Andrey Deineko
Andrey Deineko

Reputation: 52357

records.flat_map(&:to_a).map { |a| a.join(',') }
#=> ["ID,BOATY", "Name,McBoatface, Boaty", "ID,TRAINY", "Name,McTrainface, Trainy"]

Upvotes: 3

Arihant
Arihant

Reputation: 745

Hope it helps.

li = []
records.each do |rec|
    rec.each do |k,v|
      li << "#{k.to_s},#{v.to_s}".to_s
    end
end

print li

["ID,BOATY", "Name,McBoatface, Boaty", "ID,TRAINY", "Name,McTrainface, Trainy"]

Upvotes: 1

Thomas
Thomas

Reputation: 1633

records = [
  {
    ID: 'BOATY',
    Name: 'McBoatface, Boaty'
  },
  {
    ID: 'TRAINY',
    Name: 'McTrainface, Trainy'
  }
]


# strait forward code
result= []
records.each do |hash|
  hash.each do |key, value|
    result<< key.to_s
    result<< value
  end
end
puts result.inspect

# a rubyish way (probably less efficient, I've not done the benchmark)
puts records.map(&:to_a).flatten.map(&:to_s).inspect

Upvotes: 2

Related Questions