我刚刚开始使用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
答案 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