Introduction
Classes help you organize code by grouping related data and actions together.
Classes help you organize code by grouping related data and actions together.
class ClassName # code goes here end
Class names start with a capital letter.
Use end to close the class definition.
Dog.class Dog end
Person has a method greet that prints a message.class Person def greet puts "Hello!" end end
Car has an initialize method to set up new objects with make and model.class Car def initialize(make, model) @make = make @model = model end end
This program defines a class Animal with a method speak. Then it creates an object my_pet and calls speak to print a message.
class Animal def speak puts "I make a sound" end end my_pet = Animal.new my_pet.speak
Remember to use new to create an object from a class.
Instance variables start with @ and belong to each object.
Classes group related data and methods.
Class names start with a capital letter and end with end.
Use new to create objects from classes.
class followed by a capitalized name.class MyClass uses class and a capitalized name, which is correct. Options A, B, and D use wrong keywords or lowercase names.end to close blocks like classes, methods, and conditionals.end uses end. The others are not valid Ruby keywords.class Dog
def bark
"Woof!"
end
end
fido = Dog.new
puts fido.barkDog has a method bark that returns the string "Woof!".fido from Dog using new. Calling fido.bark returns "Woof!" which is printed.class cat
def meow
"Meow!"
end
endcat starts with lowercase.end keyword, method is inside class, and double quotes are valid for strings.Car with a method start that returns "Engine started". Which code correctly declares this class and method?class Car
def start
"Engine started"
end
end correctly uses class Car with capitalized name and ends with end.class Car
def start
"Engine started"
end
end defines method start returning the string "Engine started". class Car
def start()
puts "Engine started"
end
end uses puts which prints but returns nil, so not exactly the same.Pass the test and this pattern moves unknown