Author: Saim Khalid

  • Classes and Objects

    Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include −

    • Data Encapsulation
    • Data Abstraction
    • Polymorphism
    • Inheritance

    These features have been discussed in the chapter Object Oriented Ruby.

    An object-oriented program involves classes and objects. A class is the blueprint from which individual objects are created. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.

    Take the example of any vehicle. It comprises wheels, horsepower, and fuel or gas tank capacity. These characteristics form the data members of the class Vehicle. You can differentiate one vehicle from the other with the help of these characteristics.

    A vehicle can also have certain functions, such as halting, driving, and speeding. Even these functions form the data members of the class Vehicle. You can, therefore, define a class as a combination of characteristics and functions.

    A class Vehicle can be defined as −

    ClassVehicle{Number no_of_wheels
       Number horsepower
       Characters type_of_tank
       NumberCapacityFunction speeding {}Function driving {}Function halting {}}

    By assigning different values to these data members, you can form several instances of the class Vehicle. For example, an airplane has three wheels, horsepower of 1,000, fuel as the type of tank, and a capacity of 100 liters. In the same way, a car has four wheels, horsepower of 200, gas as the type of tank, and a capacity of 25 liters.

    Defining a Class in Ruby

    To implement object-oriented programming by using Ruby, you need to first learn how to create objects and classes in Ruby.

    A class in Ruby always starts with the keyword class followed by the name of the class. The name should always be in initial capitals. The class Customer can be displayed as −

    class Customer
    end
    

    You terminate a class by using the keyword end. All the data members in the class are between the class definition and the end keyword.

    Variables in a Ruby Class

    Ruby provides four types of variables −

    • Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _.
    • Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.
    • Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
    • Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).

    Example

    Using the class variable @@no_of_customers, you can determine the number of objects that are being created. This enables in deriving the number of customers.

    classCustomer@@no_of_customers =0end

    Creating Objects in Ruby using new Method

    Objects are instances of the class. You will now learn how to create objects of a class in Ruby. You can create objects in Ruby by using the method new of the class.

    The method new is a unique type of method, which is predefined in the Ruby library. The new method belongs to the class methods.

    Here is the example to create two objects cust1 and cust2 of the class Customer −

    cust1 =Customer.new
    cust2 =Customer.new

    Here, cust1 and cust2 are the names of two objects. You write the object name followed by the equal to sign (=) after which the class name will follow. Then, the dot operator and the keyword new will follow.

    Custom Method to Create Ruby Objects

    You can pass parameters to method new and those parameters can be used to initialize class variables.

    When you plan to declare the new method with parameters, you need to declare the method initialize at the time of the class creation.

    The initialize method is a special type of method, which will be executed when the new method of the class is called with parameters.

    Here is the example to create initialize method −

    classCustomer@@no_of_customers =0definitialize(id, name, addr)@cust_id = id
    
      @cust_name = name
      @cust_addr = addr
    endend

    In this example, you declare the initialize method with id, name, and addr as local variables. Here, def and end are used to define a Ruby method initialize. You will learn more about methods in subsequent chapters.

    In the initialize method, you pass on the values of these local variables to the instance variables @cust_id, @cust_name, and @cust_addr. Here local variables hold the values that are passed along with the new method.

    Now, you can create objects as follows −

    cust1 =Customer.new("1","John","Wisdom Apartments, Ludhiya")
    cust2 =Customer.new("2","Poul","New Empire road, Khandala")

    Member Functions in Ruby Class

    In Ruby, functions are called methods. Each method in a class starts with the keyword def followed by the method name.

    The method name always preferred in lowercase letters. You end a method in Ruby by using the keyword end.

    Here is the example to define a Ruby method −

    classSampledeffunction
    
      statement 1
      statement 2endend</pre>

    Here, statement 1 and statement 2 are part of the body of the method function inside the class Sample. These statments could be any valid Ruby statement. For example we can put a method puts to print Hello Ruby as follows −

    classSampledefhello
    
      puts "Hello Ruby!"endend</pre>

    Now in the following example, create one object of Sample class and call hello method and see the result −

    #!/usr/bin/rubyclassSampledefhello
    
      puts "Hello Ruby!"endend# Now using above class to create objects
    object =Sample.new object.hello

    This will produce the following result −

    Hello Ruby!
    

    Simple Case Study

    Here is a case study if you want to do more practice with class and objects.

    Ruby Class Case Study

  • Syntax

    Let us write a simple program in ruby. All ruby files will have extension .rb. So, put the following source code in a test.rb file.

    #!/usr/bin/ruby -w
    
    puts "Hello, Ruby!";

    Here, we assumed that you have Ruby interpreter available in /usr/bin directory. Now, try to run this program as follows −

    $ ruby test.rb
    

    This will produce the following result −

    Hello, Ruby!
    

    You have seen a simple Ruby program, now let us see a few basic concepts related to Ruby Syntax.

    Whitespace in Ruby Program

    Whitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements. Interpretations of this sort produce warnings when the -w option is enabled.

    Example

    a + b is interpreted as a+b ( Here a is a local variable)
    a  +b is interpreted as a(+b) ( Here a is a method call)
    

    Line Endings in Ruby Program

    Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as &plus;, −, or backslash at the end of a line, they indicate the continuation of a statement.

    Ruby Identifiers

    Identifiers are names of variables, constants, and methods. Ruby identifiers are case sensitive. It means Ram and RAM are two different identifiers in Ruby.

    Ruby identifier names may consist of alphanumeric characters and the underscore character ( _ ).

    Reserved Words

    The following list shows the reserved words in Ruby. These reserved words may not be used as constant or variable names. They can, however, be used as method names.

    BEGINdonextthen
    ENDelseniltrue
    aliaselsifnotundef
    andendorunless
    beginensureredountil
    breakfalserescuewhen
    caseforretrywhile
    classifreturnwhile
    definself__FILE__
    defined?modulesuper__LINE__

    Here Document in Ruby

    “Here Document” refers to build strings from multiple lines. Following a << you can specify a string or an identifier to terminate the string literal, and all lines following the current line up to the terminator are the value of the string.

    If the terminator is quoted, the type of quotes determines the type of the line-oriented string literal. Notice there must be no space between << and the terminator.

    Here are different examples −

    #!/usr/bin/ruby -w
    
    print <<EOF
       This is the first way of creating
       here document ie. multiple line string.
    EOF
    
    print <<"EOF";# same as aboveThis is the second way of creating
       here document ie. multiple line string.EOF
    
    print <<EOC                 # execute commands
    	echo hi there
    	echo lo there
    EOC
    
    print <<"foo",<<"bar"# you can stack themI said foo.
    foo
    	I said bar.
    bar
    

    This will produce the following result −

       This is the first way of creating
       her document ie. multiple line string.
       This is the second way of creating
       her document ie. multiple line string.
    hi there
    lo there
    
      I said foo.
      I said bar.

    Ruby BEGIN Statement

    Syntax

    BEGIN {
       code
    }
    

    Declares code to be called before the program is run.

    Example

    #!/usr/bin/ruby
    
    puts "This is main Ruby Program"BEGIN{
       puts "Initializing Ruby Program"}

    This will produce the following result −

    Initializing Ruby Program
    This is main Ruby Program
    

    Ruby END Statement

    Syntax

    END {
       code
    }
    

    Declares code to be called at the end of the program.

    Example

    #!/usr/bin/ruby
    
    puts "This is main Ruby Program"END{
       puts "Terminating Ruby Program"}BEGIN{
       puts "Initializing Ruby Program"}

    This will produce the following result −

    Initializing Ruby Program
    This is main Ruby Program
    Terminating Ruby Program
    

    Ruby Comments

    A comment hides a line, part of a line, or several lines from the Ruby interpreter. You can use the hash character (#) at the beginning of a line −

    # I am a comment. Just ignore me.
    

    Or, a comment may be on the same line after a statement or expression −

    name = "Madisetti" # This is again comment
    

    You can comment multiple lines as follows −

    # This is a comment.
    # This is a comment, too.
    # This is a comment, too.
    # I said that already.
    

    Here is another form. This block comment conceals several lines from the interpreter with =begin/=end −

    =begin
    This is a comment.
    This is a comment, too.
    This is a comment, too.
    I said that already.
    =end
  • Environment Setup

    Local Environment Setup

    If you are still willing to set up your environment for Ruby programming language, then let’s proceed. This tutorial will teach you all the important topics related to environment setup. We would recommend you to go through the following topics first and then proceed further −

    • Ruby Installation on Linux/Unix − If you are planning to have your development environment on Linux/Unix Machine, then go through this chapter.
    • Ruby Installation on Windows − If you are planning to have your development environment on Windows Machine, then go through this chapter.
    • Ruby Command Line Options − This chapter list out all the command line options, which you can use along with Ruby interpreter.
    • Ruby Environment Variables − This chapter has a list of all the important environment variables to be set to make Ruby Interpreter works.

    Popular Ruby Editors

    To write your Ruby programs, you will need an editor −

    • If you are working on Windows machine, then you can use any simple text editor like Notepad or Edit plus.
    • VIM (Vi IMproved) is a very simple text editor. This is available on almost all Unix machines and now Windows as well. Otherwise, your can use your favorite vi editor to write Ruby programs.
    • RubyWin is a Ruby Integrated Development Environment (IDE) for Windows.
    • Ruby Development Environment (RDE) is also a very good IDE for windows users.

    Interactive Ruby (IRb)

    Interactive Ruby (IRb) provides a shell for experimentation. Within the IRb shell, you can immediately view expression results, line by line.

    This tool comes along with Ruby installation so you have nothing to do extra to have IRb working.

    Just type irb at your command prompt and an Interactive Ruby Session will start as given below −

    $irb
    irb 0.6.1(99/09/16)
    irb(main):001:0>defhello
    irb(main):002:1> out ="Hello World"
    irb(main):003:1> puts out
    irb(main):004:1>endnil
    irb(main):005:0> hello
    HelloWorldnil
    irb(main):006:0>

    Do not worry about what we did here. You will learn all these steps in subsequent chapters.

    What is Next?

    We assume now you have a working Ruby Environment and you are ready to write the first Ruby Program. The next chapter will teach you how to write Ruby programs.

  • Overview

    Ruby is a pure object-oriented programming language. It was created in 1993 by Yukihiro Matsumoto of Japan.

    You can find the name Yukihiro Matsumoto on the Ruby mailing list at www.ruby-lang.org. Matsumoto is also known as Matz in the Ruby community.

    Ruby is “A Programmer’s Best Friend”.

    Ruby has features that are similar to those of Smalltalk, Perl, and Python. Perl, Python, and Smalltalk are scripting languages. Smalltalk is a true object-oriented language. Ruby, like Smalltalk, is a perfect object-oriented language. Using Ruby syntax is much easier than using Smalltalk syntax.

    Features of Ruby

    • Ruby is an open-source and is freely available on the Web, but it is subject to a license.
    • Ruby is a general-purpose, interpreted programming language.
    • Ruby is a true object-oriented programming language.
    • Ruby is a server-side scripting language similar to Python and PERL.
    • Ruby can be used to write Common Gateway Interface (CGI) scripts.
    • Ruby can be embedded into Hypertext Markup Language (HTML).
    • Ruby has a clean and easy syntax that allows a new developer to learn very quickly and easily.
    • Ruby has similar syntax to that of many programming languages such as C++ and Perl.
    • Ruby is very much scalable and big programs written in Ruby are easily maintainable.
    • Ruby can be used for developing Internet and intranet applications.
    • Ruby can be installed in Windows and POSIX environments.
    • Ruby support many GUI tools such as Tcl/Tk, GTK, and OpenGL.
    • Ruby can easily be connected to DB2, MySQL, Oracle, and Sybase.
    • Ruby has a rich set of built-in functions, which can be used directly into Ruby scripts.

    Tools You Will Need

    For performing the examples discussed in this tutorial, you will need a latest computer like Intel Core i3 or i5 with a minimum of 2GB of RAM (4GB of RAM recommended). You also will need the following software −

    • Linux or Windows 95/98/2000/NT or Windows 7 operating system.
    • Apache 1.3.19-5 Web server.
    • Internet Explorer 5.0 or above Web browser.
    • Ruby 1.8.5

    This tutorial will provide the necessary skills to create GUI, networking, and Web applications using Ruby. It also will talk about extending and embedding Ruby applications.

    What is Next?

    The next chapter guides you to where you can obtain Ruby and its documentation. Finally, it instructs you on how to install Ruby and prepare an environment to develop Ruby applications.

  • Ruby Tutorial

    What is Ruby?

    Ruby is an open-source and high-level programming language, which is known for its simplicity and developer-friendliness. This is designed by Yukihiro Matsumoto with the purpose of making programming more enjoyable and productive for developers. Ruby includes a lot of key features like its Object-Oriented, Dynamic Typing, Readable Syntax, and a large Standard Library collection.

    Why to Learn Ruby?

    Ruby is a simple and expressive programming language, which provides various advantages to programmers, especially in fields like web development, automation tasks, scripting, etc. Here in the following, we will discuss its features and advantages.

    • Simplicity and Readable Syntax: Ruby’s syntax is designed in a very clean and concise way, which provides easy-to-read, write, and understand code leading to increased productivity by allowing developers to focus more on problem-solving rather than complex syntax.
    • Powerful Frameworks: Ruby also provides popular web development frameworks like Ruby on Rails (RoR), which is a popular framework used for web development allowing developers to build complex applications more efficiently.
    • Strong Community and Ecosystem: Ruby also provides a supportive and active community, where users will find many libraries, tools, and resources. RubyGems repository offers a large set of collections of reusable code and libraries to accelerate development.
    • Prototyping: This is great for prototyping ideas and applications as its dynamic nature allows rapid iterations. This makes Ruby ideal for startups and developers.

    Characteristics of Ruby

    The following are important characteristics of Ruby programming:

    • Object-oriented:
      Ruby is purely object-oriented, which means everything in Ruby is an object including primitive data types like numbers, strings, and nil.
    • Dynamic Typing and Concise Syntax:
      In ruby, you don’t need to explicitly declare any variable types, it is automatically determined at runtime, providing greater flexibility and its syntax is to be designed clean, simple, and human-readable.
    • Automatic Memory Management (Garbage Collection):
      Ruby also provides flexibility by automatically managing memory allocation and deallocation with garbage collection, helping reduce complexity and the risk of memory leaks.
    • Large Standard Library:
      Ruby also has a large standard library consisting of many built-in classes and methods, covering a wide range of tasks like file I/O and data manipulation, etc.
    • Metaprogramming:
      It also allows to modify objects and classes during runtime. This provides flexibility as programs can dynamically be altered thus supporting Metaprogramming.

    Ruby Hello, World! Program

    To start with any programming, the very basic program is to print “Hello World!” Here we will print it in Ruby by using the puts. Below is an example of code to print “Hello, World!”. You can try it using the Edit & Run button.

    # Ruby code to print Hello, World!
    puts "Hello, World!"

    Ruby Online Compiler

    We provide an easy, user-friendly, and fast Ruby online compiler, where you can write, save, run, and share your Ruby programs. Click on this link to open it: Ruby Online Compiler

    Applications of Ruby

    Ruby is a general-purpose programming language, which has a wide range of applications that have been discussed in the given following.

    • Web and API Development:
      Ruby on Rails is one of the most popular frameworks for web development, where Rails is a full-stack web framework, which is used for building dynamic and database-driven websites. Example GitHub, Shopify, Airbnb, etc. Similarly, it is also commonly used for building RESTful APIs and web services. example Stripe and Twilio.
    • Scripting and Automation:
      Ruby’s concise syntax and rich libraries make it the best choice for creating command-line tools, scripting, and automating repetitive tasks like file manipulation, data processing, System administration and testing, etc.
    • Data Extraction and Analysis:
      Ruby’s powerful libraries like RMagick for image processing, Nokogiri for parsing HTML and XML, and HTTParty for making HTTP requests help in web scraping, data extraction, and analysis.
    • DevOps and System Administration:
      Ruby is also used in DevOps and system administration tasks, with tools like Chef (a configuration management tool) and Puppet, which are built using Ruby.
    • Application Development:
      Unlike C++ or Python, ruby can also used for developing various applications like game development, E-commerce Development, Social Media Platforms, etc.

    Jobs or Careers with Ruby

    Ruby’s nature of rapid development cycle, ease of use, and ability to handle interactions make it a great choice for site and application development, although it’s not used for large-scale platforms. Here in the following, we will discuss a few of its career options.

    • Ruby on Rails and Ruby Developer
    • Software Engineer
    • DevOps Engineer
    • Full-Stack Developer
    • Data Analyst/Scientist
    • Product and Community Manager
    • API Developer
    • Game Developer

    Target Audience: Who should Learn Ruby?

    This tutorial covers all key information from basic to advanced concepts related to Ruby scripting languages, which is useful for both aspiring and experienced programmers, web developers especially those who work with Ruby on Rails, Full-Stack Developers, also for Startups and Entrepreneurs as it allows for rapid development of web applications, Developers who interested in prototyping, test and driven developers and DevOps developers etc.

    Prerequisites to Learn Ruby

    Before you start practicing with various types of examples given in this tutorial, we are making an assumption that you are already aware of computer programs like basic computer literacy, basic knowledge of text editors and IDEs (like VS Code and Sublime Text, etc.), familiarity with version control system like git.

  • Loan EMI Calculator

    Calculate monthly EMI for a loan.
    COMPUTE, ACCEPT, DISPLAY.

    Formula: EMI=P×R×(1+R)N(1+R)N−1EMI = \frac{P \times R \times (1+R)^N}{(1+R)^N – 1}EMI=(1+R)N−1P×R×(1+R)N​

    Where:

    • P = Principal Loan Amount
    • R = Monthly Interest Rate
    • N = Number of Months

  • Employee Database

    Store employee records and display them.
    FILE handling, WRITE/READ, PERFORM.

           IDENTIFICATION DIVISION.
    
       PROGRAM-ID. EMPLOYEE-DB.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT EMP-FILE ASSIGN TO 'EMPLOYEE.DAT'
           ORGANIZATION IS LINE SEQUENTIAL.
       DATA DIVISION.
       FILE SECTION.
       FD EMP-FILE.
       01 EMP-REC.
          05 EMP-ID     PIC 9(4).
          05 EMP-NAME   PIC A(20).
          05 EMP-SAL    PIC 9(6).
       WORKING-STORAGE SECTION.
       01 WS-EOF PIC X VALUE "N".
       PROCEDURE DIVISION.
           OPEN OUTPUT EMP-FILE
               MOVE 1001 TO EMP-ID
               MOVE "ALICE" TO EMP-NAME
               MOVE 50000 TO EMP-SAL
               WRITE EMP-REC
               MOVE 1002 TO EMP-ID
               MOVE "BOB" TO EMP-NAME
               MOVE 60000 TO EMP-SAL
               WRITE EMP-REC
           CLOSE EMP-FILE
           OPEN INPUT EMP-FILE
           PERFORM UNTIL WS-EOF = "Y"
               READ EMP-FILE
                   AT END MOVE "Y" TO WS-EOF
                   NOT AT END DISPLAY EMP-REC
               END-READ
           END-PERFORM
           CLOSE EMP-FILE
           STOP RUN.

    Explanation:

    • Writes employee data into a file EMPLOYEE.DAT.
    • Then reads back and displays the stored records.
    • Simulates a small HR employee database.

  • Sales Billing System

    Calculate total bill with discount and tax.
    Arithmetic operations, COMPUTE, ACCEPT/DISPLAY.

           IDENTIFICATION DIVISION.
    
       PROGRAM-ID. BILLING.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 ITEM-NAME    PIC A(20).
       01 PRICE        PIC 9(5)V99.
       01 QUANTITY     PIC 9(3).
       01 TOTAL        PIC 9(6)V99.
       01 DISCOUNT     PIC 9(6)V99.
       01 NET-AMOUNT   PIC 9(6)V99.
       PROCEDURE DIVISION.
           DISPLAY "ENTER ITEM NAME: " ACCEPT ITEM-NAME
           DISPLAY "ENTER PRICE: " ACCEPT PRICE
           DISPLAY "ENTER QUANTITY: " ACCEPT QUANTITY
           COMPUTE TOTAL = PRICE * QUANTITY
           IF TOTAL &gt; 5000
               COMPUTE DISCOUNT = TOTAL * 0.10
           ELSE
               COMPUTE DISCOUNT = TOTAL * 0.05
           END-IF
           COMPUTE NET-AMOUNT = TOTAL - DISCOUNT
           DISPLAY "ITEM: " ITEM-NAME
           DISPLAY "TOTAL: " TOTAL
           DISPLAY "DISCOUNT: " DISCOUNT
           DISPLAY "NET AMOUNT: " NET-AMOUNT
           STOP RUN.

    Explanation:

    • Accepts price & quantity, calculates bill.
    • Applies discount based on purchase amount.
    • Simulates a retail billing system.
  • ATM Simulation Project

    Mimic ATM operations (deposit, withdraw, check balance, exit).

    PERFORM loops, IF-ELSE, arithmetic.

           IDENTIFICATION DIVISION.
    
       PROGRAM-ID. ATM.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 BALANCE     PIC 9(6)V99 VALUE 5000.00.
       01 AMOUNT      PIC 9(6)V99.
       01 CHOICE      PIC 9.
       01 EXIT-FLAG   PIC X VALUE "N".
       PROCEDURE DIVISION.
       MAIN-PARA.
           PERFORM UNTIL EXIT-FLAG = "Y"
               DISPLAY "1. CHECK BALANCE"
               DISPLAY "2. DEPOSIT"
               DISPLAY "3. WITHDRAW"
               DISPLAY "4. EXIT"
               ACCEPT CHOICE
               EVALUATE CHOICE
                   WHEN 1 DISPLAY "BALANCE: " BALANCE
                   WHEN 2
                        DISPLAY "ENTER DEPOSIT: " ACCEPT AMOUNT
                        ADD AMOUNT TO BALANCE
                        DISPLAY "UPDATED BALANCE: " BALANCE
                   WHEN 3
                        DISPLAY "ENTER WITHDRAWAL: " ACCEPT AMOUNT
                        IF AMOUNT &gt; BALANCE
                            DISPLAY "INSUFFICIENT FUNDS"
                        ELSE
                            SUBTRACT AMOUNT FROM BALANCE
                            DISPLAY "UPDATED BALANCE: " BALANCE
                        END-IF
                   WHEN 4 MOVE "Y" TO EXIT-FLAG
                   WHEN OTHER DISPLAY "INVALID CHOICE"
               END-EVALUATE
           END-PERFORM.
           STOP RUN.

    Explanation:

    • PERFORM UNTIL → creates a menu-driven system.
    • EVALUATE → works like switch-case in modern languages.
    • Handles deposits, withdrawals, exit.
  • Marksheet Processing System

    Input marks of students and calculate grade.
    IF-ELSE, arithmetic, ACCEPT/DISPLAY.

           IDENTIFICATION DIVISION.
    
       PROGRAM-ID. MARKSHEET.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 STUDENT-NAME PIC A(20).
       01 MARKS        PIC 9(3).
       01 GRADE        PIC A.
       PROCEDURE DIVISION.
           DISPLAY "ENTER STUDENT NAME: "
           ACCEPT STUDENT-NAME
           DISPLAY "ENTER MARKS (0-100): "
           ACCEPT MARKS
           IF MARKS &gt;= 90
               MOVE "A" TO GRADE
           ELSE IF MARKS &gt;= 75
               MOVE "B" TO GRADE
           ELSE IF MARKS &gt;= 50
               MOVE "C" TO GRADE
           ELSE
               MOVE "F" TO GRADE
           END-IF
           DISPLAY "STUDENT: " STUDENT-NAME
           DISPLAY "GRADE  : " GRADE
           STOP RUN.

    Explanation:

    • Uses conditions to assign grades A, B, C, F.
    • Simple logic but reflects real-world evaluation.