RubyBeginner
RubyBeginner

Reputation: 319

Ruby class using attr_accessor and initialize method

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?

Upvotes: 4

Views: 2339

Answers (1)

rudolph9
rudolph9

Reputation: 8119

Question 1

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

Question 2

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.

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 Object class in Ruby, see here for documentation on the Object class.

Upvotes: 5

Related Questions