Ruby Tutorial
Ruby CGI
Ruby Advanced
In Ruby, like in many programming languages, an "environment" refers to the context in which a program runs. This context includes things like environment variables, the current directory, command-line arguments, and loaded libraries.
Here's a brief overview of some important aspects of the Ruby environment:
1. Environment Variables:
Environment variables are global settings that affect your system's behavior. In Ruby, you can access environment variables through the ENV
object:
puts ENV['PATH'] # Prints the PATH environment variable
You can also set environment variables for the duration of your program:
ENV['MY_VARIABLE'] = 'my value' puts ENV['MY_VARIABLE'] # Prints "my value"
2. Current Directory:
The current directory is the directory from which your Ruby script is being run. You can get the current directory with Dir.pwd
:
puts Dir.pwd # Prints the current directory
You can also change the current directory with Dir.chdir
:
Dir.chdir('/path/to/new/directory') puts Dir.pwd # Prints the new directory
3. Command-Line Arguments:
Command-line arguments are inputs that you can pass to your Ruby script from the command line. These are accessible through the ARGV
array:
# Suppose you run: ruby my_script.rb arg1 arg2 puts ARGV[0] # Prints "arg1" puts ARGV[1] # Prints "arg2"
4. Loaded Libraries:
In Ruby, you can load libraries (also known as gems) with require
:
require 'json' # Loads the json library
The $LOAD_PATH
(or $:
) variable contains the list of directories that Ruby will check when you call require
. If you're developing a library, you might need to add its directory to $LOAD_PATH
.
5. Ruby Version:
The RUBY_VERSION
constant contains the version of Ruby that's currently running:
puts RUBY_VERSION # Prints the Ruby version, e.g. "2.7.1"
Remember, the environment in which your Ruby script runs can greatly affect its behavior. It's often important to control this environment to ensure that your script works as expected.
Ruby environment variables:
# Accessing an environment variable puts ENV['MY_VARIABLE']
Managing Ruby gems in the environment:
gem
command to manage Ruby gems, which are packages or libraries.# Install a gem gem install my_gem # List installed gems gem list # Remove a gem gem uninstall my_gem
Managing dependencies in Ruby environment:
# Gemfile source 'https://rubygems.org' gem 'my_gem', '~> 1.0'
# Install dependencies bundle install
Ruby environment path:
PATH
environment variable specifies the directories where executable files are located.# Add Ruby binaries to the PATH export PATH="$PATH:/path/to/ruby/bin"