Ruby has a rich set of built-in data types that provide developers with flexible options for storing and manipulating data. Here are some of the most common data types in Ruby:
.jpg)
1. Numbers
In Ruby, numbers can be represented as integers or floating-point numbers. Integers are whole numbers, while floating-point numbers have a decimal component.
Here are some examples of working with numbers in Ruby:
Integers# Assign an integer value to a variable num1 = 10 # Perform arithmetic operations sum = num1 + 5 difference = num1 - 3 product = num1 * 2 quotient = num1 / 3 # Use modulo to get the remainder remainder = num1 % 3 # Check if a number is even or odd is_even = num1.even? # returns true is_odd = num1.odd? # returns false # Increment and decrement a number num1 += 1 # equivalent to num1 = num1 + 1 num1 -= 1 # equivalent to num1 = num1 - 1
Floating-Point Numbers
# Assign a floating-point value to a variable num2 = 3.14 # Perform arithmetic operations sum = num2 + 2.5 difference = num2 - 1.2 product = num2 * 4 quotient = num2 / 1.5 # Round a floating-point number to a specific number of decimal places rounded_num = num2.round(1) # returns 3.1 # Convert a floating-point number to an integer integer_num = num2.to_i # returns 3
Working with numbers is a fundamental aspect of programming, and Ruby provides many built-in methods and operators for performing arithmetic operations and working with numerical data
Dear Programmer this is basic, please click here for more number programs and reallife uses of programs
2. Strings
Strings are a sequence of characters enclosed in single or double quotes. They can be manipulated in various ways, such as concatenating, splitting, and formatting.
greeting = "Hello, world!" name = "Alice"
3. Booleans
Booleans represent the truth values true and false. They are often used in conditional statements and loops.
is_raining = true has_car = false
4. Symbols
Symbols are immutable objects used to represent names or values. They are often used as keys in hashes.
status = :success user_type = :admin
5. Arrays
Arrays are ordered collections of objects. They can contain any type of object, including other arrays.
fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5]
6. Hashes
Hashes are collections of key-value pairs. They are unordered and are accessed using their keys.
person = { name: "Alice", age: 30, city: "New York" }
7. Nil
nil represents the absence of a value. It is often used to represent uninitialized variables or to indicate that a method did not return a value.
result = nil
These are some of the most commonly used data types in Ruby. Knowing how to work with them effectively is essential for building robust and flexible Ruby programs.
0 Comments