简体   繁体   中英

How do I write the contents of a hash to a file in Ruby?

I have a hash that looks as follows:

character = {"Name: " => "#$name", "Weapon: " => "#$weapon", "Armor: " => "#$armor"}

I want to print each key and each value to a file so that it looks something like this.

Name: Templar
Weapon: Sword
Armor: Heavy Armor

I would like to use a basic method so that I understand what is going on. I've read that there are some modules that do this for you, such as Marshal, but I would like a basic method that involves beginner-level code.

This should work for you. I would recommend reading up more on Files and iterating through hashes yourself first though.

yourfile = "/some/path/file.txt"
File.open(yourfile, 'w') do |file|
  character.each{ |k, v| file.write("#{k}: #{v}\n") }
end

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