Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading YAML file in Ruby

Tags:

ruby

yaml

I apologize for the amateur question, I'm still learning. I'm trying to pull information from a YAML file in Ruby. I thought that because I had pushed the information to an array, all I would have to is print the array. I know that's not the case, but I couldn't find anything in the documentation when I looked.

require "yaml"

class BankAccount

attr_accessor :first_name, :last_name, :address, :your_account

def initialize
    @your_account = []
    open()
end

def open
    if File.exist?("accountinfo.yml")
    @your_account = YAML.load_file("accountinfo.yml")
    end
end

def save
    File.open("accountinfo.yml", "r+") do |file|
        file.write(your_account.to_yaml)
    end
end

def new_account(first_name, last_name, address)
    puts "Enter your first name:"
    first_name = gets.chomp
    puts "Enter your last name"
    last_name = gets.chomp
    puts "Enter your address:"
    address = gets.chomp
end

def account_review(your_account)
    puts @your_acccount
end

def run
    loop do
        puts "Welcome to the bank."
        puts "1. Create New Account"
        puts "2. Review Your Account Information"
        puts "3. Check Your Balance"
        puts "4. Exit"
        puts "Enter your choice:"
            input = gets.chomp
            case input
            when '1'
                new_account(first_name, last_name, address)
            when '2'
                account_review(your_account)
            when '4'
                save()
                break
            end
    end
end

end
bank_account = BankAccount.new
bank_account.run
like image 838
cpppatrick Avatar asked Aug 20 '26 11:08

cpppatrick


1 Answers

When I'm facing something like this, I find it easiest to use irb to see what a YAML file looks like after it is loaded. Sometimes it can be in a format subtly different to what you were expecting.

In the same directory, on the command line, run irb.

You then have an interactive Ruby console where you can run commands.

require 'pp' - this helps you see output more easily.

Then:

your_account = YAML.load_file("accountinfo.yml")
pp your_account

In the code above, it appears that in your new_account method, you're not actually setting these attributes on @your_account, and in the save method you're writing an undefined variable to yaml.

Save should be:

file.write(@your_account.to_yaml) 

New account should end with:

@your_account[:first_name] = first_name
@your_account[:last_name] = last_name
@your_account[:address] = address
like image 163
stef Avatar answered Aug 23 '26 20:08

stef