Predefined Constants in Ruby Language
Ruby is a versatile and dynamic programming language known for its flexibility and readability. To make coding
more efficient and readable, Ruby provides a set of predefined constants. These constants are built-in values that can be accessed throughout your Ruby programs without the need for explicit declaration. In this article, we’ll explore some of the most commonly used predefined constants in Ruby, along with examples of how to use them.true
andfalse
Ruby’s true
and false
constants represent boolean values. They are used extensively for logical operations and conditional statements.
is_ruby_fun = true
is_python_fun = false
if is_ruby_fun
puts "Ruby is fun!"
else
puts "Ruby is not fun."
end
nil
nil
represents the absence of a value, similar to null
in other programming languages. It is often used to indicate the absence of data or an uninitialized variable.
my_variable = nil
if my_variable.nil?
puts "The variable is nil."
else
puts "The variable has a value."
end
STDIN
,STDOUT
, andSTDERR
These constants represent the standard input, standard output, and standard error streams, respectively. They are used for interacting with the command line.
puts "Enter your name: "
name = STDIN.gets.chomp
STDOUT.puts "Hello, #{name}!"
STDERR.puts "This is an error message."
PI
Math::PI
is a predefined constant representing the mathematical constant Pi (π). It is part of the Math
module.
radius = 5
circumference = 2 * Math::PI * radius
puts "The circumference of a circle with a radius of #{radius} is #{circumference}."
RUBY_VERSION
andRUBY_PLATFORM
These constants provide information about the Ruby environment. RUBY_VERSION
gives the current Ruby version, while RUBY_PLATFORM
indicates the platform on which Ruby is running.
puts "Running Ruby version #{RUBY_VERSION} on #{RUBY_PLATFORM}."
ARGV
ARGV
is an array containing command-line arguments passed to a Ruby script. It is especially useful for building command-line utilities.
puts "You provided the following arguments:"
ARGV.each do |arg|
puts arg
end
__FILE__
and__LINE__
__FILE__
represents the name of the current source file, while __LINE__
returns the current line number.
puts "This code is in file: #{__FILE__}, line: #{__LINE__}"
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.