Here is an example of binding.pry
in action.
require 'pry'
def calculate_area(width, height)
result = 0
binding.pry
if (height < 0)
puts ("ERROR in input")
else
result = height * width
puts ("Calculation check: #{result}")
end
return result
end
height = -10
width = 12
calculate_area(height, width)
As programs get larger we look for ways to better organise our code. Objects help us manage complexity. Object Oriented programming provides a means to accurately represent "real world concepts" and "business logic".
A class is a type of object. It's like a bluebrint or a template. For example, a person is a class, but you and the person next to you are objects. You both have an eye colour, height and favourite food. You both also perform actions like cook, eat and breathe. When we're writing code we refer to the things an object has as attributes (name, location) and the things an object does (drink, greet) as methods.
Often we want to represent objects in our code like 'students'. What attributes would a student have? What methods would a student have?
Here is an example of a Car class.
class Car
def initialize(make, year, mileage)
@make = make
@year = year
@mileage = mileage
end
def drive(distance)
@mileage += distance
end
def description()
return "Make: #{@make}, Year: #{@year}, Mileage: #{@mileage}"
end
end
To instantiate a an object we use .new
work_car = Car.new('Toyota', 2018, 5000)
We can then access methods on the car object.
work_car = Car.new('Toyota', 2018, 5000)
puts ("The work car is #{work_car.description()}")
work_car.drive(100)
puts ("The work car is #{work_car.description()}")