Reputation: 319
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
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?
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?
Upvotes: 4
Views: 2339
Reputation: 8119
The attr_accessor
method is a short cut to declaring variable accessible outside the
block within the method.
The initializer
method in ruby is the method to be called when someone initializes
something of that class, i.e. chipotle = Restaurant.new 'Chipotle', 'Mexican', 8.00
Array
is 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 the Array
class. You do not need to do any kind of special inheritance in order the use the Array
class 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.
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 Object
class in Ruby, see here for documentation on the Object
class.
Upvotes: 5