The Ruby Variable, Class, And Constant Name Guide
Posted on
As I’m learning Ruby, I’m having a somewhat hard time remembering all the specific Ruby syntax. So this is more of a guide to myself (by writing it out, I’m hoping I’ll remember it better), and you’re welcome to follow along…
Local Variables
Examples:
- name
- student_id
- graduation2012
- _photo
A local variable is a variable that is given local scope and is accessible from a declared method or block in which it is declared. In Ruby, local variables start with a lower-case letter or an underscore, and can have numbers in the name. camelCase is not really used for local variables in Ruby, so use the underscores instead.
Instance Variables
Examples:
- @name
- @student_id
- @graduation2012
- @_photo
An instance variable is a variable defined in a class, for which each object of the class has a separate copy. Instance variables in Ruby are declared with an “@” sign in front of the variable name.
Class Variables
Examples:
- @@name
- @@student_id
- @@YEAR
An class variable is a variable defined in a class, for each each object of the class has a single copy. If you’d like to learn more about the difference between class and instance variables, here is a great explanation. Class variables start with “@@” signs in from of the variable name.
Global Variables
Examples:
- $name
- $_photo
- $Year
- $COLLEGE
A global variable is accessible in every scope. In Ruby, the global variables start with a “$” sign in front of the variable name.
Class Names
Examples:
- MyClass
- School
- Student
In Ruby, class names start with a capital letter and could be CamelCase.
Constant Names
Examples:
- CREDITS
- YEARS_TO_GRADUATE
- PI
Constants in Ruby are all caps.
Wow, writing these out really did help me remember all of these