📚 Scripting Languages Tutorial

Scripting Languages

Learn scripting languages (Ruby, Perl, TCL and Tk) with simple explanations, examples, techniques and practical notes.

← Back to Scripting Languages

Datatypes in Ruby

A data type specifies what kind of value is stored in a variable. Ruby is a dynamically typed language. This means we do not need to declare the data type of a variable.

Ruby automatically determines the data type based on the value assigned to the variable.

Example

name = "Madhu"          # String
age = 21                # Integer
salary = 25000.50       # Float
is_student = true       # Boolean

Ruby supports the following data types, those are

  1. Integer
  2. Float
  3. String
  4. Symbol
  5. Boolean
  6. Nil
  7. Array
  8. Hash
  9. Range

1. Integer

An Integer is used to store all the numbers, including positive and negative, without decimal points.

Examples: 10, 20, 100, -50

2. Float

Float is used to store all the numbers, including positive and negative, with decimal points.

Examples: 10.5, 25.75, 100.50

3. String

A String is a collection of characters enclosed within single or double quotation marks.

Examples: 'Ruby', "Madhu", "Hello World"

4. Symbol

A Symbol is a special type of identifier that begins with a colon (:). It is commonly used as a name or key in Ruby programs.

Example:
name = :madhu
branch = :CSE

5. Boolean

Boolean data types represent only two values: true and false.

Example:
is_student = true

6. Nil

nil represents the absence of a value in Ruby.

Example:
var = nil

7. Array

An Array is used to store multiple values in a single variable. Array elements are enclosed within square brackets [].

Example:
students = ["Madhu", "Ravi", "Naveen"]
puts students[0]
puts students[1]
Output:
Madhu
Ravi

8. Hash

A Hash stores data in the form of key-value pairs. It is similar to a dictionary in Python.

Example:
student = {
  name: "Madhu",
  age: 21,
  branch: "CSE"
}
puts student[:name]
puts student[:age]
Output:
Madhu
21

9. Range

A Range represents a sequence of values between a starting value and an ending value.

Ruby provides two range operators:

  • ..   Includes the ending value.
  • ...   Excludes the ending value.
Example:
numbers = (1..5)     # prints 1 2 3 4 5
numbers = (1...5)    # prints 1 2 3 4