Author: Saim Khalid

  • Classes and Objects

    class Person
    attr_accessor :name, :age # creates getter & setter

    def initialize(name, age) # constructor
    @name = name
    @age = age
    end

    def introduce
    “Hi, I’m #{@name} and I’m #{@age} years old.”
    end
    end

    p1 = Person.new(“Ali”, 25)
    puts p1.introduce
    class defines a blueprint.

    @name and @age are instance variables.

    initialize runs when object is created.
    Output:


    Hi, I’m Ali and I’m 25 years old.

  • Methods

    def greet(name)
    return “Hello, #{name}!”
    end

    puts greet(“Ayesha”)
    def starts a method, end closes it.

    return gives back a value.
    Output:


    Hello, Ayesha!

  • Loops

    While Loop

    i = 1
    while i <= 5
      puts i
      i += 1
    end
    
    • Runs while condition is true.
      Output:
    1
    2
    3
    4
    5

    For Loop

    for n in 1..5
      puts n
    end
    
    • 1..5 means range from 1 to 5.
      Output: 1 2 3 4 5

    Each Loop

    [1, 2, 3, 4, 5].each do |num|
      puts num * 2
    end
    
    • Iterates over each element.
      Output:
    2
    4
    6
    8
    10
    

  • Conditions

    age = 18

    if age >= 18
    puts “You are an adult.”
    elsif age >= 13
    puts “You are a teenager.”
    else
    puts “You are a child.”
    end
    if … elsif … else … end is used for decision making.
    Output:


    You are an adult.

  • Hashes (Dictionary / Map)

    student = { “name” => “Ali”, “age” => 22, “grade” => “A” }
    puts student[“name”] # Ali
    student[“age”] = 23 # update
    puts student.inspect
    Hashes store key-value pairs.

    Keys can be strings “name” or symbols :name.
    Output:


    Ali
    {“name”=>”Ali”, “age”=>23, “grade”=>”A”}

  • Arrays

    fruits = [“apple”, “banana”, “cherry”]

    puts fruits[0] # apple
    puts fruits.length # 3
    fruits << “mango” # Add new element
    puts fruits.inspect # Show complete array
    Arrays store multiple values.

    Index starts from 0.

    << means “append”.

    Output:


    apple
    3
    [“apple”, “banana”, “cherry”, “mango”]

  • Variables and Data Types

    name = “Saim” # String
    age = 25 # Integer
    height = 5.9 # Float
    is_student = true # Boolean

    puts “Name: #{name}, Age: #{age}, Height: #{height}, Student: #{is_student}”
    Ruby is dynamically typed → no need to mention string, int, etc.

    {} → used inside strings for interpolation (inserting values).

    Output:


    Name: Saim, Age: 25, Height: 5.9, Student: true

  • Hello World

    puts “Hello, World!”
    puts → Prints text with a new line at the end.

    “Hello, World!” is a string.
    Output:


    Hello, World!

  • Ruby Cheatsheet

    The Ruby Cheatsheet provides the fundamentals of Ruby programming. It helps students and developers to build the projects and prepare for the interviews. Go through the cheat sheet and learn the concepts. Thus, this improves the coding skills.

    • Basic Syntax
    • Variables
    • Operators
    • Comments
    • String
    • String Interpolation
    • If-else Statement
    • Classes and Objects
    • Break Statements
    • Ruby Blocks
    • Modules
    • Array
    • Hashes
    • Ranges
    • Regular Expression
    • Exception Handling
    • Commonly Used Library

    1. Basic Syntax

    This is the basic syntax of the Ruby programming language that displays the text using puts and print.

    puts "Hello, World!"
    print "Tutorialspoint!"

    2. Variables

    Variables are used for the memory location. Ruby supports various types of variable −

    # Defining the variables
    x =10# integer
    y =20.5# float
    puts x + y
    

    3. Operators

    The operators are the symbol that tells the compiler to perform logical tasks.

    OperatorsDescriptionExample
    Arithmetic OperatorsThis is basic mathematical operations.‘a + b’, ‘a – b’, ‘a * b’, ‘a / b’, ‘a % b’
    Relational OperatorsThis compares two values.‘a == b’, ‘a != b’, ‘a > b’, ‘a < b’, ‘a >= b’, ‘a <= b’
    Logical OperatorsThis combine the conditional statements.‘a && b’, ‘a || b’, ‘!a’
    Bitwise OperatorsThis perform in the bit level.‘a & b’, ‘a | b’, ‘a ^ b’, ‘~a’, ‘a << b’, ‘a >> b’
    Assignment OperatorsThis assign the values to the variables.‘a = b’, ‘a += b’, ‘a -= b’, ‘a *= b’, ‘a /= b’, ‘a %= b’

    Below are the some examples of operators in Ruby programming language −

    # Arithmetic Operators# Addition
    puts 8+18# Subtraction  
    puts 9-3# Multiplication  
    puts 7*6# Division
    puts 20/4# Comparison Operators# Greater than
    puts 10>5# Equal to  
    puts 10==5# Not equal to
    puts 10!=5

    4. Comments

    Comments are used to show the information. The single-line comment is denoted by “#” whereas multi-line comments are written using the =begin and =end keywords.

    # This is a single-line comment=begin
    multi-line comment
    =end

    5. String

    The strings are used to print the text. In Ruby, strings are represented using both single and double quotes.

    # Strings
    str1 ="Hello"
    str2 ='World!'
    puts str1 +" "+ str2
    

    6. String Interpolation

    The string interpolation is the process of inserting the values with the help of expression inside the curly braces #{}.

    name ="Tutorialspoint!"
    puts "Welcome to #{name}!"

    7. If-else Statement

    The if-else statement is a part of the control structure used to execute the logic conditionally, based on whether the condition is true or false.

    age =18if age >=18
      print "You are eligible for vote."else
      print "You are are not eligible for vote."end

    8. Classes and Objects

    Classes and objects are fundamental concepts of object-oriented programming. A class defines the blueprint for an object, whereas an object is an instance of a class.

    classPersondefinitialize(name, id)@name= name
    
    @id= id
    enddeffun
    puts "My name is #{@name} and I am #{@id} years old."endend
    person =Person.new("Sanjay",25) person.fun

    9. break Statements

    In Ruby, the break statement terminates the program loop.

    num =[1,2,3,4,5,6,7,8,9,10]
    num.eachdo|num|if num ==7
    
    puts "The loop break at the number #{num}"breakend
    puts "The processing number is #{num}"end puts "Loop ended."

    10. Ruby Blocks

    The blocks represent the anonymous function in Ruby that is passed into the methods. The block can be declared using a single-line or multi-line block.

    times { puts "Hello, Block!"}

    11. Modules

    In Ruby, a module is a collection of methods and constants that can be used to organize and structure code.

    # example of modulesmoduleMathHelpersdefsquare(x)
    
    x * x
    endendincludeMathHelpers puts square(4)

    12. Array

    In Ruby, an array defines the ordered, indexed collection of objects. The object holds the data types such as String, Integer, Fixnum, Hash, Symbol, and even other Array objects.

    arr =[10,20,30,40,50]
    arr.each{|i| puts i }

    13. Hashes

    The hashes are similar to dictionaries by defining key−value pairs.

    hash ={ name:"Ruby", id:3323}
    puts hash[:name]

    14. Ranges

    The ranges are data types that show a sequence of values.

    (1..5).each{|i| puts i }

    15. Regular Expression

    Regular Expression is defined by the special sequence of characters that help users to find the set of string matches or particular syntax held in the program.

    /pattern//pattern/im# option can be specified%r!/usr/local!# general delimited regular expression

    16. Exception Handling

    In Ruby, an exception handling is the process of handling the error raised in the program. These errors occur during the execution of the program. In simple, unexpected, or unwanted events.

    beginraise# block where exception raiserescue# block where exception rescueend

    17. Commonly Used Library

    Here, we are providing the example of the JSON library.

    require'json'
    data ={ name:"Ruby", type:"Programming Language"}
    puts JSON.generate(data)

  • Associated Tools

    Standard Ruby Tools

    The standard Ruby distribution contains useful tools along with the interpreter and standard libraries −

    These tools help you debug and improve your Ruby programs without spending much effort. This tutorial will give you a very good start with these tools.

    • RubyGems −RubyGems is a package utility for Ruby, which installs Ruby software packages and keeps them up-to-date.
    • Ruby Debugger −To help deal with bugs, the standard distribution of Ruby includes a debugger. This is very similar to gdb utility, which can be used to debug complex programs.
    • Interactive Ruby (irb) −irb (Interactive Ruby) was developed by Keiju Ishitsuka. It allows you to enter commands at the prompt and have the interpreter respond as if you were executing a program. irb is useful to experiment with or to explore Ruby.
    • Ruby Profiler −Ruby profiler helps you to improve the performance of a slow program by finding the bottleneck.

    Additional Ruby Tools

    There are other useful tools that don’t come bundled with the Ruby standard distribution. However, you do need to install them yourself.

    • eRuby: Embeded Ruby −eRuby stands for embedded Ruby. It’s a tool that embeds fragments of Ruby code in other files, such as HTML files similar to ASP, JSP and PHP.
    • ri: Ruby Interactive Reference −When you have a question about the behavior of a certain method, you can invoke ri to read the brief explanation of the method.

    For more information on Ruby tool and resources, have a look at Ruby Useful Resources.