Predefined Variables in Ruby Language
Ruby is a versatile and dynamic programming language known for its simplicity and flexibility. It offers a wide
range of features that make it an attractive choice for both beginners and experienced developers. One of these features is the use of predefined variables, which are built-in variables that serve various purposes in Ruby. In this article, we will explore some of the most commonly used predefined variables in Ruby, along with examples of their usage.- $global_variable
- This is a global variable that can be accessed from anywhere in the Ruby code.
- It starts with a dollar sign (‘$’) followed by a variable name.
- Example:
$global_var = "I'm a global variable"
def print_global
puts $global_var
end
print_global # Output: "I'm a global variable"
- $stdin and $stdout
- These predefined variables represent the standard input and output streams.
- They are commonly used for reading user input and displaying output.
- Example:
print "Enter your name: "
user_name = gets.chomp
$stdout.puts "Hello, #{user_name}!"
- $stderr
- This variable represents the standard error stream and is used for error messages.
- Example:
$stderr.puts "This is an error message."
- $LOAD_PATH ($:)
- $LOAD_PATH is an array containing a list of directories where Ruby looks for scripts and libraries.
- It is useful for specifying custom paths for your Ruby files.
- Example:
$LOAD_PATH << "/path/to/your/library"
require "your_library"
- ARGV
- ARGV is an array that holds command-line arguments passed to a Ruby script.
- It allows you to interact with the arguments provided when running your program.
- Example:
# ruby script.rb arg1 arg2
arg1, arg2 = ARGV
puts "First argument: #{arg1}"
puts "Second argument: #{arg2}"
- ENV
- ENV is a hash that contains the current environment variables.
- It is useful for accessing system-specific information or configuration.
- Example:
puts "Your username is: #{ENV['USER']}"
These predefined variables are an integral part of the Ruby language, providing developers with powerful tools to handle various aspects of programming, from user input to system interaction. Understanding when and how to use these variables can greatly enhance your Ruby programming skills.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.