← Back to Ruby Course | Chapter 9: OOP | Lesson 1 of 7

Class Basics

A class is a blueprint that describes what things of one kind know and can do, like a plan for a toy. You use it to make many toys.

In this page:

  1. Class Basics
Syntax
ruby
class ClassName
  # attributes and methods
end

object = ClassName.new

Class Basics

A Ruby class is defined with class ClassName ... end, bundling data and behavior into a single blueprint that objects are created from with .new.

Class names conventionally use CamelCase, unlike methods and variables which use snake_case. Every value in Ruby, including numbers and strings, is an object of some class.

Note: Ruby class names must start with a capital letter -- this is enforced by the language, not just a style convention.

Example: Class Basics

markup
class Dog
  def bark
    puts "Woof!"
  end
end

rex = Dog.new
rex.bark
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Naming a class in lowercase, such as class dog, which is a syntax error because class names are constants.
  2. Calling Dog.bark instead of creating an object with Dog.new first.
  3. Forgetting end after the class or a method.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.