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:
Syntax
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
class Dog
def bark
puts "Woof!"
end
end
rex = Dog.new
rex.bark
Login to try C/C++/Java/PHP code in the editor
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
- Naming a class in lowercase, such as
class dog, which is a syntax error because class names are constants. - Calling
Dog.barkinstead of creating an object withDog.newfirst. - Forgetting
endafter the class or a method.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: