Ruby Basics

Ruby Basics

Ruby is a general-purpose language that can be used for various programming tasks, from simple scripts to large-scale web applications. It is often used for web development.

In this article, I'll take you on a journey through the fundamental concepts of Ruby

Difference between Ruby and Ruby on Rails

Ruby and Ruby on Rails (RoR) are two distinct but related things. Ruby is a programming language, while Ruby on Rails (RoR) is a web application framework built using the Ruby programming language.

Hello, world!

Let's write a simple "Hello, world!" program in Ruby:

puts "Hello, world!"

In Ruby, puts is a method that prints a string to the console followed by a newline character. So when we run the code above, it will print the string "Hello, world!" to the console and add a new line character at the end.

This program is often used as a first program when learning a new programming language because it is a simple and easy way to verify that the programming environment is set up correctly and to get familiar with the language's basic syntax.

Variables in Ruby

In Ruby, variables are used to store data that can be referenced and manipulated throughout the program. There are three types of variables in Ruby: local variables, instance variables, and class variables.

Local variables

They are variables that are declared inside a method or block and can only be accessed within that particular scope.

def greet
  name = "John"
  puts "Hello, #{name}!"
end

greet

This method doesn't take any arguments but contains a local variable name with the value "John". It then prints out a greeting message using string interpolation with the name variable. Finally, the greet method is invoked outside the method definition.

Instance variables

They are variables that are declared with the @ symbol and can be accessed across different methods within a class instance. For example:

class Person
  def initialize(name)
    @name = name
  end

  def say_hello
    puts "Hello, #{@name}!"
  end
end

person = Person.new("John")
person.say_hello

This code demonstrates the principles of object-oriented programming in Ruby, where we define classes with methods and create instances of those classes to work with the defined behavior.

Class variables

They are variables that are declared with the @@ symbol and can be accessed across different instances of a class:

class Person
  @@count = 0

  def initialize(name)
    @name = name
    @@count += 1
  end

  def self.count
    @@count
  end
end

person1 = Person.new("John")
person2 = Person.new("Jane")
puts Person.count

In the above code snippet, we've defined a class Person with a class-level variable @@count, an initialize method, and a class method self.count.

Declaring a variable in Ruby

To declare a variable in Ruby, we assign a value to it using the equal sign =operator. For example:

my_variable = "Hello, world!"

This creates a new local variable called my_variable and assigns it the value "Hello, world!".

To use the variable later inside the program, we can simply refer to it by name:

puts my_variable

The example below shows a running Ruby program that uses a variable:

my_variable = "Hello, world!"
puts my_variable

Integers in Ruby

In Ruby, integers are built-in data types that are used to represent whole numbers. Integers can be positive, negative, or zero, and they can be used in mathematical operations like addition, subtraction, multiplication, and division.

To create an integer variable in Ruby, we assign a number to it using the equal sign = operator. For example:

my_integer = 42

This creates a new variable called my_integer and assigns it the value 42.

To use the integer later in the program, we refer to it by name and perform operations on it. For example:

my_integer = 42
puts my_integer + 10   
puts my_integer * 2

This code creates a variable called my_integer and assigns it the value 42, it then performs some mathematical operations on it using the + and * operators.

Pseudovariables in Ruby

In Ruby, pseudovariables are special variables that have predefined meanings and can't be reassigned. There are three pseudovariables in Ruby: self, true, and false.

  • self: self is a pseudovariable that refers to the current object or instance. It is often used to refer to the object that a method is being called on. For example:
class MyClass
  def my_method
    puts self
  end
end

obj = MyClass.new
obj.my_method

In this example, the my_method method uses self to refer to the current instance of the MyClass class.

  • true and false: true and false are pseudovariables that represent the boolean values of true and false, respectively. They are often used in conditional statements and logical expressions. For example:

      if true
        puts "This lesson is amazing"
      end
    
      if false
        puts "This lesson is not amazing"
      end
    

In this example, the first if statement will always be evaluated as true, so the code inside the block will be executed. The second if statement will always be evaluated as false, so the code inside the block will not be executed.

To use pseudovariables in Ruby programs, we simply refer to them by name as shown in the examples above. We can't assign values to pseudovariables because they have predefined meanings in the language.

Strings in Ruby

In Ruby, strings are a built-in data type that is used to represent text. Strings are enclosed in either single quotes or double quotes, and they can contain any combination of letters, numbers, and special characters.

To create a string variable in Ruby, we simply enclose the text in quotes and assign it to a variable using the equal sign = operator. For example:

my_string = "Hello, world!"

This creates a new variable called my_string and assigns it the value "Hello, world!".

To use the string later in the program, we can refer to it by name and perform operations on it. For example:

my_string = "Hello, world!"
puts my_string.upcase   
puts my_string.reverse

This code creates a variable called my_string with the value, "Hello, world!" and then performs some operations on it using built-in string methods like upcase and reverse. The results are printed to the console using the puts method.

Array in Ruby

In Ruby, arrays are used to store a collection of related data items of any data type, such as strings, integers, or even other arrays. To create an array, we can use square brackets [] and separate the values with commas. For example:

my_array = ["apple", "banana", "orange"]

This creates an array called my_array with three string values: apple, banana, and orange.

We can access individual elements of an array using square brackets and the index of the element we want to access. Note that in Ruby, array indices start at 0. For example:

my_array = ["apple", "banana", "orange"]
puts my_array[0]  # Output: apple
puts my_array[2]  # Output: orange

In this example, we use the square bracket notation to access the first element of the my_array array, which is "apple", and the third element of the array, which is "orange".

Iterators in Ruby

In Ruby, iterators are methods that allow us to loop over a collection of data, such as an array or a hash. There are many built-in iterators in Ruby, and we can also define our custom iterators.

The most common built-in iterators in Ruby are each, map, and select. Here's how we can use them:

each

The each iterator allows us to loop over each element in a collection and perform some action on each element. For example:

my_array = ["apple", "banana", "orange"]
my_array.each do |fruit|
  puts fruit.upcase
end

This code creates an array called my_array and then uses the each iterator to loop over each element in the array. The |fruit| part of the code is a block parameter that specifies the name of the variable that will represent each element in the array as it is being looped over. In this case, we use the puts method to print each element in uppercase letters.

map

The map iterator allows us to loop over each element in a collection and transform each element using a block of code. For example:

my_array = [1, 2, 3]
new_array = my_array.map do |num|
  num * 2
end
puts new_array.inspect

This code creates an array my_array with three integer values and then uses the map iterator to loop over each element in the array and multiply it by 2. The result is new array called new_array which contains the transformed values.

select

The select iterator allows us to loop over a collection and select only the elements that meet a certain condition. For example:

my_array = [1, 2, 3, 4, 5]
new_array = my_array.select do |num|
  num.even?
end
puts new_array.inspect

This code creates an array my_array with five integer values and then uses the select iterator to loop over each element in the array and select only the even numbers. The result is a new array called new_array that contains only the even numbers.

Ranges in Ruby

In Ruby, ranges are a way to represent a sequence of values between a start and an endpoint. Ranges can be created using the .. , ... operators.

Here's an example of creating a range and iterating over its values:

range = 1..5
range.each do |num|
  puts num
end

In this example, a range is created. That includes the values from 1 to 5 inclusive. The each method is then called on the range object to iterate over each value in the range, and the value is printed to the console using puts.

Conclusion

Ruby is an exceptional programming language that is renowned for its remarkable simplicity, unparalleled flexibility, and exceptional expressiveness.

Happy Coding!