Ruby - 使我的代码对象定向

时间:2016-04-07 04:32:03

标签: ruby oop

我刚刚开始使用OOP,并且正在努力研究如何实现它。我无法使用hash.new方法计算出如何创建类的实例。它是一个基本程序,它从用户获取输入并将其存储在哈希中。然后我计划将哈希推入数组以利用索引。以下是代码

class Customer

    def initialize(id, name, address, phone, email, bank_balance)
        @id = id
        @name = name
        @address = address
        @phone = phone
        @email = email
        @bank_balance = bank_balance
    end
end

puts "Would you like to create an account?"
answer = gets.chomp

loop do

    new_hash = {}
    if answer.downcase.start_with?('y')

        puts "Enter your name"
        name = gets.chomp.downcase
        new_hash['name'] = name

        puts "Enter your address"
        address = gets.chomp.downcase
        new_hash['address'] = address

        puts "Enter your ph number"
        number = gets.chomp
        number = number.split.join
        new_hash['number'] = number

        puts "Enter your email"
        email = gets.chomp.downcase
        new_hash['email'] = email       

        puts "Enter your bank balance"
        bank_balance = gets.chomp
        bank_balance = "$" + '%.2f' % bank_balance
        new_hash['bank_balance'] = bank_balance

        customer << new_hash

        binding.pry
        puts "Thankyou, details successfully Added"

        break
    else
        break
    end
end

1 个答案:

答案 0 :(得分:0)

你应该删除initialize(...)中的所有内容,而不是使用 attr_accessor :name, :address, :phone, :email, :bank_balance)将其写在初始化语句之上 有关attr_accessor的更多信息,请参阅此帖子What is attr_accessor in Ruby? 通过阅读attr_reader和attr_writer

来跟进

然后,您可以在其余代码中为这些初始化变量赋值。 你将通过运行Customer.new

来打电话给你的班级

您可以通过将gets.chomp值分配给其他方法来获取更多代码,然后您可以执行类似

的操作
class Customer
  attr_accessor :name, :address, :phone
  def initialize
    @name = ''
    @address = ''
    @phone = ''
  end

  def name
    puts "Enter your name"
    name = gets.chomp.downcase
  end
  def address
   puts "Enter your address"
    address = gets.chomp.downcase
  end
  def phone
   puts 'enter your phone'
   phone = gets.chomp
   phone = phone.split.join
  end
  def all
    name
    address
    phone  
  end
end
customer = Customer.new
customer.all