简体   繁体   中英

Save hash in the csv ruby

I have hash:

users = {
'name' => name,
        'last_name' => last_name,
        'photo' => photo,
        'address' => address,
}

Save in csv:

CSV.open("users.csv", "a") {|csv| users.to_a.each {|elem| csv << elem}}

Output:

 name, Jake
 last_name,Kallen
photo, http://avs.ru/leto_3434.jpg
address, NEW YORK
name, Dan
 last_name,Leans
photo, http://avs.ru/leto_3423.jpg
address, NEW YORK

I need to get the file:

Jake,Kallen,http://avs.ru/leto_3434.jpg,NEW YORK

How to change my code to get what I need? Help me please.

UPD: I forgot to point out that a lot of users

This should do the trick:

CSV.open("users.csv", "a") do |csv|
  csv << users.values_at('name', 'last_name', 'photo', 'address')
end

You want to extract the hash values by key and pass it to the csv object as an array, which values_at returns.

If you have more than one user, please update the sample data in your question.

CSV.open("users.csv", "a") {|csv|
  csv << users.values
}

I think, you need this. If users hash will contains other data - csv will take it to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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