簡體   English   中英

在Ruby中讀取YAML文件

[英]Reading YAML file in Ruby

對於業余問題,我深表歉意,但我仍在學習中。 我正在嘗試從Ruby的YAML文件中提取信息。 我以為,因為我已將信息推送到數組,所以我所要做的就是打印數組。 我知道不是這種情況,但是當我查看文檔時找不到任何東西。

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

當我遇到這樣的問題時,我發現最簡單的方法是使用irb查看加載后的YAML文件的外觀。 有時,它的格式可能與您期望的格式略有不同。

在同一目錄中的命令行上,運行irb

然后,您將擁有一個交互式Ruby控制台,您可以在其中運行命令。

require 'pp'這樣可以幫助您更輕松地查看輸出。

然后:

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

在上面的代碼中,似乎在new_account方法中,您實際上並未在@your_account上設置這些屬性,而在save方法中,您正在向yaml寫入未定義的變量。

保存應為:

file.write(@your_account.to_yaml) 

新帳戶應以:

@your_account[:first_name] = first_name
@your_account[:last_name] = last_name
@your_account[:address] = address

您從未真正設置過變量。 self.前綴的二傳手self. ,否則您將只創建一個具有相同名稱的局部變量。 此外,您根本不需要設置your_acccount

def new_account
  puts "Enter your first name:"
  self.first_name = gets.chomp
  puts "Enter your last name"
  self.last_name = gets.chomp
  puts "Enter your address:"
  self.address = gets.chomp

  self.your_account = [first_name, last_name, address]
end

另一個問題是您的代碼永遠不會調用open 這意味着一切正常,直到結束程序並重新啟動它為止。 只需致電open ,再致電account_review即可解決該問題。

如果您使用的是Rails,這是讀取YAML文件的簡單方法(標題說明)

# Load the whatever_config from whatever.yml
whatever_config = YAML.load(ERB.new(File.read(Rails.root.join("config/whatever.yml"))).result)[Rails.env]

# Extract the foo variable out
foo = whatever_config['foo']

我想我真的不明白您的問題是什么嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM