Serialize an array of hashes

craig

New Member
#1
I have an array of hashes:
Mã:
  records = [
    {
      ID: 'BOATY',
      Name: 'McBoatface, Boaty'
    },
    {
      ID: 'TRAINY',
      Name: 'McTrainface, Trainy'
    }
  ]
I'm trying to combine them into an array of strings:
Mã:
["ID,BOATY","Name,McBoatface, Boaty","ID,TRAINY","Name,McTrainface, Trainy"]
This doesn't seem to do anything:
Mã:
irb> records.collect{|r| r.each{|k,v| "\"#{k},#{v}\"" }}
#=> [{:ID=>"BOATY", :Name=>"McBoatface, Boaty"}, {:ID=>"TRAINY", :Name=>"McTrainface, Trainy"}]
What am I missing?
 

Admin

Administrator
Thành viên BQT
#2
You try:

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

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top