Ruby: Intro to Variable Scope Types
Beginner’s Ruby knowledge, with a focus on variable scope.
Hey there my coding friends. Today, I thought I’d talk about the coding language Ruby. For anyone out there who just started learning it or is interested in learning the language, this blog is for you! So listen up! I will mainly focus on Ruby variables and getting to know the different types. Let’s unveil this Ruby mystery!
Roots of Ruby
Ruby got its roots in the mid-1990s, where it was created by Yukihiro “Matz” Matsumoto in Japan. It’s dynamically typed and can support multiple programming paradigms like functional, object-oriented, and procedural programming.
Ruby is an object-oriented language. Each value that is typed is an object.
Variable Scopes
There are four types of variable scope: global, class, instance, and local.
Global Variables
When typed a global variable you will start with a “$” sign. Anytime a global variable is reassigned, it alters the variable’s global status. It’s not recommended to use global variables, as it can make a program cryptic. Also note, uninitialized Global variables have the value nil.
Instance Variables
The syntax for instance variables is to begin them with an “@” sign. An instance variable has the value “nil” before initialization.
Class Variables
Class variables begin with “@@” signs. They can be accessed throughout the entire class they have been created inside of.
Local Variables
Local variables begin with lowercase letters or an “_”. The Ruby docs say: “The scope of a local variable ranges from class, module, def, or do to the corresponding end or from a block’s opening brace to its close brace {}.:”
An example of local scope we can refer to here is from the above example of the Dog class (pictured in the last example above): id, name, and breed are all local variables.
Unlike global and instance variables, local variables don’t have the value “nil” before initialization.
Here’s one more example to visually see local variables in action in Ruby.
Conclusion
Thanks for reading about Ruby! I hope this gave you a nice intro to the world of Ruby, specifically different types of variables scope. Keep the learning going, check out the Ruby docs, and I hope you’ll find your way to learn some more of this fine language!