Working toward making a small command line script in Ruby, where the
user provides a few pieces of information related to restaurants, and
computed info gets returned.
Currently I have the following code:
class Restaurant
attr_accessor :name :type :avg_price
def initialize(name, type, avg_price)
@name = name
@type = type
@avg_price = price
end
end
Question 1
If we used attr_accessors method to declare type, and price, and name
Why is the Initialize method necessary? Is this because we need to set the
inputed values to it?
Question 2
There is a sub-class called RestaurantList followed by < Array in the code. What is the function of this?
The Array class is not defined in the code? Is it a built in class in ruby called Array? If so, what exactly does it do?
Question 1
The
attr_accessormethod is a short cut to declaring variable accessible outside theblock within the method.
The
initializermethod in ruby is the method to be called when someone initializessomething of that class, i.e.
chipotle = Restaurant.new 'Chipotle', 'Mexican', 8.00Question 2
Arrayis indeed a class built into Ruby, (built in classes generally referred to as the Ruby Standard Library, see here for the MRI 1.9.3 documentation on theArrayclass. You do not need to do any kind of special inheritance in order the use theArrayclass though. The language is defined in a manor such that things such as string, hashes, arrays, and other commonly used classes do not need to be inherited.That said, these are able to be overloaded. Don’t be surprised the day you find something that looks like an array but has alternate functionality.
Other Notes
One thing to keep in mind when you approach Ruby programming is that everything is an object. You will often hear this but it difficult to comprehend when you first dive but still important to keep in mind that everything can be mapped back to the
Objectclass in Ruby, see here for documentation on theObjectclass.