2015-11-19 46 views
0

我有一個數組 loan = %w(100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000)我想.sample這個數組並存儲它以備後用。將一個隨機選取的元素保存在一個數組中

我創建一個ATM程序,並正在創建貸款類..

來源:

require_relative 'loanamount.rb' #Where the above array is stored 

private #Is part of an ATM class, which has nothing to do with this section 

class Loan < ATM 
    attr_accessor :credit 
     def initialize(score) 
      @score = 0 
     end 
    end 

    def loan_info 
     puts <<-END.gsub(/^\s*>/, ' ') 
      > 
      >Hello and welcome to the credit station 
      >Please choose from the list below 
      >Would you like to Apply for a loan '1' 
      >Check credit score '2' 
      >Go back '3' 
      > 
     END 
     input = gets.chomp 
     case input.to_i 
     when 1 
      apply_credit 
     when 2 
      check_score 
     else 
      redirect 
     end 
    end 

    def apply_credit 
     if @score >= 640 
      accepted 
     else 
      denied_loan 
     end 
    end 

    def accepted 
     puts "You have been accepted for a #{loan.sample} loan which will be added to your bank account" 
     puts <<-END.gsub(/^\s*>/, ' ') 
      > 
      >Which account would you like to add that to? 
      >Checking Account '1' 
      >Savings Account '2' 
      > 
     END 
     input = gets.chomp 
     case input.to_i 
     when 1 
      @checking_account += "#{loan}"#I want to add the amount that loan.sample gave 
      puts "#{loan} has been added to your checking account, your new balance is #{@checking_account}" 
      puts "Your card will now be returned for security purposes." 
      exit 
     when 2 
      @savings_account += "#{loan}" #Not completed yet.. 
     end 
    end 

因此,例如:

loan = ["100", "200", "300"] 
puts "You are given #{loan.sample}" 
puts "You now have *amount*" #I want to be able to call the amount that loan.sample gave me" 

回答

1

你需要知道Ruby在字符串和數字之間有着非常嚴格的區別。預期下面的代碼將無法正常工作:

@checking_account += "#{loan}" 

這是試圖將一個字符串添加到什麼大概是一個數字,雖然我不能看到@checking_account被初始化。

你大概的意思是這樣的:

loan_amount = loan.sample 
@checking_account += loan_amount 

puts "Your loan for %d was approved, your balance is now %d" % [ 
    loan_amount, 
    @checking_account 
] 

這也要求loan是數字數組:

loan = ["100", "200", "300"] # Incorrect, is strings 
loan = [ 100, 200, 300 ] # Correct, is numbers 

像PHP和JavaScript將字符串和數字之間自動轉換爲必要的一些語言,或者經常任意使用,但如果您嘗試,Ruby不會並且會投訴。

當你要開始使用結構更好地組織你的數據,例如一張紙條:

@accounts = Hash.new(0) 
@accounts[:checking] += loan_amount 
+0

我知道,代碼會在所有輸出的整個陣列,或什麼都沒有。你回答我的問題,所以謝謝你 – 13aal

+1

希望有所幫助。 Ruby對於事物的嚴格程度可能有點令人困惑,但你會得到它的訣竅。 – tadman

+0

我越來越好這就是所有重要的大聲笑! – 13aal

相關問題