In Ruby, when we create a class, we can define attribute accessor and attribute readers.
class Car
attr_reader :model, :top_speed
attr_accessor :current_speed
def initialize(model, top_speed)
@model = model
@top_speed = top_speed
@current_speed = 0
end
def drive(speed_to_drive_at)
@current_speed = speed_to_drive_at
end
end
The class definition above will allow us to write the following code:
# we can first create a new instance of car
my_car = Car.new('Audi S5', 300)
# and then we can read the value of the car's model or top_speed
puts my_car.model # outputs 'Audi S5'
puts my_car.top_speed # outputs 300
Could you please explain how readers and accessors work?
In Javascript, you can create classes simply by defining a constructor function and initializing your class with it.
But how do we create instance methods in Javascript? -- see TODO
comment in code snippet below
What's the difference between how we create instance methods in Javascript vs in Ruby?
function Car(model, top_speed){
this.model = model;
this.top_speed = top_speed;
this.current_speed = 0;
}
// TODO: instance method, drive, goes here
// changes the current speed of the car to the one specified
The constructor method above will allow us to write the following code:
// we can first create a new instance of car
let my_car = Car.new('Audi S5', 300)
// now we want to be able to change the my_car's current speed
// by calling the `drive` method
my_car.drive(100)
console.log(my_car.current_speed) // must output 100