EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Ruby

Ruby Basic Concepts

Keywords or reserved words are special words in a programming language that have predefined meanings and are used for certain internal processes. These words cannot be used as identifiers such as variable names, object names, or constants. Attempting to use these reserved words as identifiers will result in a compile-time error.

Example of Invalid Use of Keywords

# Ruby program to illustrate Keywords

# This is an incorrect use of the keyword 'if'
# It cannot be used as a variable name
if = 30

# Here 'if' and 'end' are keywords used incorrectly
# Using them will result in a syntax error
if if >= 18
  puts "You are eligible to drive."
end

Compile-Time Error:

Error(s), warning(s):

example.rb:4: syntax error, unexpected '='

if = 30

    ^

example.rb:9: syntax error, unexpected '>='

if if >= 18

        ^

example.rb:11: syntax error, unexpected keyword_end, expecting end-of-input

Common Ruby Keywords

Ruby has a total of 41 reserved keywords. Here are some of the most common ones and their uses:

Ruby Basic Concepts
KeywordDescription
__ENCODING__The script encoding of the current file.
__LINE__The line number in the current file.
__FILE__The path to the current file.
BEGINRuns code before any other in the current file.
ENDRuns code after all other code in the current file.
aliasCreates an alias for a method.
andLogical AND with lower precedence than &&.
classDefines a new class.
defDefines a method.
doBegins a block of code.
endEnds a syntax block such as a class, method, or loop.
ifConditional statement.
moduleDefines a module.
nextSkips to the next iteration of a loop.
nilRepresents “no value” or “undefined”.
returnExits from a method and optionally returns a value.
selfRefers to the current object.
trueBoolean true value.
whileCreates a loop that executes while a condition is true.

Example of Using Keywords Correctly

Here’s a simple example demonstrating the correct use of some Ruby keywords:

# Ruby program to illustrate the use of Keywords

#!/usr/bin/ruby

# Defining a class named 'Person'
class Person

  # Defining a method using 'def' keyword
  def introduce
    # Printing a statement using 'puts'
    puts "Hello! I'm learning Ruby."
  end

# End of the method
end

# End of the class
end

# Creating an object of the class 'Person'
student = Person.new

# Calling the method using the object
student.introduce

Output:

Hello! I'm learning Ruby.
End of lesson.