2015-11-19 41 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

相关问题