我也是 Ruby 的新手,但这是我的简单实现:
class Restaurant
attr_accessor :name, :type, :avg_price
def initialize(name, type, avg_price)
@name = name
@type = type
@avg_price = Float(avg_price)
end
end
class RestaurantsList < Array
def read_from_keyboard
print "Restaurant name: "
name = gets.chomp
print "Restaurant type: "
type = gets.chomp
print "Restaurant average price: "
avg_price = gets.chomp
self << Restaurant.new( name, type, avg_price )
end
def print_list
puts sprintf("%17s %15s %s", "Name |", "Type |", "Avg price |")
self.each { |e| puts sprintf("%15s |%14s |%10d |", e.name, e.type, e.avg_price)}
end
end
restaurants_list = RestaurantsList.new
loop do
print "1 - add restaurant, 2 - print list, 3 - exit : "
answer = Integer(gets.chomp)
case answer
when 1
restaurants_list.read_from_keyboard
when 2
restaurants_list.print_list
when 3
break
end
end