Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ruby as an Object-Oriented Programming
2.1.
Syntax:
2.2.
Program:
2.3.
Output:
3.
Regex and Range in Ruby language
3.1.
Example:
4.
Methods in Ruby that can be used with Regex
5.
Types of regular expression
6.
Modifiers for regular expression
7.
What Is The Regex Object And How to use it?
8.
Frequently Asked Questions
8.1.
What kinds of things can Ruby be used for?
8.2.
Why should you learn the Ruby programming language?
8.3.
What is the difference between Ruby and Python?
8.4.
What is the result of a regex match?
8.5.
What is the definition of a regex pattern?
9.
Conclusion
Last Updated: Mar 27, 2024

Regex and Range in Ruby

Author Ishita mishra
0 upvote

Introduction

Inspired by LispSmalltalk, and Perl Ruby is a dynamic and robust programming language with a complicated but expressive grammar. It comes with a comprehensive and powerful API in its core class library. Ruby is an object-oriented programming language that may also be used for procedural and functional programming.

Many developers opt for Ruby to construct applications rapidly because of its clean and easy-to-understand code. In this article, we will discuss Ruby as object-oriented programming as well as understand range and Regex in Ruby. 

Ruby as an Object-Oriented Programming

Let's start with the fact that Ruby is an entirely object-oriented programming language. Even the most fundamental values in Ruby, such as characters, numbers, and even true and false, are objects. 

Syntax:

def initialize (m,n)
      @m = m
      @n = n
end

Objects are real-life instances that are divided into two categories namely, data and methods. Once we define the attributes of our data, then we need to access it by using methods.

Let us understand this concept in detail through an example.

Program:

#Ruby program to learn the concept of
# Access Method


class Student
        def initialize(student_name, subject_name)
              @student_name = student_name
              @subject_name = subject_name
        end
        # Defining Methods
        def return_name
              return @student_name  
        end
        def return_subject
              return @subject_name
        end
end


#creating objects
Object1 = Student.new('Abhishek' , 'Physics')
Object2 = Student.new('Aman' , 'English')
puts  'Student name for Object1: ' + Object1.return_name
puts  'Subject name for Object1: ' + Object1.return_subject
puts  'Student name for Object2: ' + Object2.return_name
puts 'Subject name for Object2:  ' + Object2.return_subject

Output:

Student name for Object1: Abhishek
Subject name for Object1: Physics
Student name for Object2: Aman
Subject name for Object2: English

Regex and Range in Ruby language

Regex stands for ‘regular expressions.’ A regular expression represents a string of characters that defines a search pattern. It allows us to find specific ways inside a string. Validation and parsing are two applications of ruby Regex. Between two forward slashes, Ruby Regex expressions are declared. In contrast, the values between two endpoints are represented by a range. Without having to type them all out, we may utilize ranges to match numerous letters or numbers.

Example:

# search for the word ‘my’
“Welcome, to my channel!” =~ /my/

If the word was found (successful match), this provides the index of the first occurrence; otherwise nil. We could use the String#include? Function if we don't care about the index.

The match method is another technique to see if a string matches a Regex:
Example:

# Ruby program of Regex
# check whether the word is present in the string or not
if “Welcome, to my channel!”.match(/my/)
    puts “match found.”
end
You can also try this code with Online Ruby Compiler
Run Code

Methods in Ruby that can be used with Regex

.scan() - Look for all the Regex matches in a string. Returns an array of data that has been matched. It's vital to remember that even if there's just one match, the array will still have one element.

.match() - If a match is detected, the method produces a MatchData object; otherwise, it returns nil. The MatchData object comes out to be true in a boolean context. The MatchData object evaluates the text that was matched in a string context.

.sub() and .gsub() - Substitute a different string for the matched string, supplied as a second parameter. The sole difference between .sub() and .gsub() is that the former substitutes the first match it encounters, while the latter does it globally (for each detected match).

.split() - Left and right of the Regex match, split the string.

Types of regular expression

Character ranges can be specified using a variety of short expressions. They can be broadly divided into positive and negative forms.

Positive form for specifying character ranges:

  • \d is equivalent to [0-9]
  • \w is the same as [0-9a-zA-Z_]
  • \s represents white space

Negative form for specifying character ranges:

  • \D is anything but a number
  • \W is everything except [0-9a-zA-Z_]
  • \S is anything but a space

The dot character (.) matches everything except new lines. If you wish to look for the character, you must first escape it.

Modifiers for regular expression

We can use modifiers to match several characters:

  • +: used for representing 1 or more characters
  • ?: used for only 0 and 1 character
  • *: used for representing 0 or more characters
  • i: used for ignoring case while matching a text
  • m: used for matching multiple lines as well as recognizing new lines as standard characters
  • x: used for ignoring whitespace and allowing comments in normal expressions
  • {x,y}: used for the number of characters between x and y

What Is The Regex Object And How to use it?

The command /regex/ generates a new object of the Regex class. You can save it as a variable and use it again and again, or you can use the literal Regex directly. Ruby has various methods for determining whether a Regex match (part of) a string.

Regex object can be created in two ways:

  1. A literal notation: In this method, parameters are separated by slashes and are not included in quotation marks.
  2. A constructor: This method slashes separate parameters that are not enclosed in quotation marks.

Regular expression objects can be created by using the following three ways:

// literal notation
let reg = /pq+r/i;

// constructor having first argument as string pattern
let reg = new RegExp(‘pq+r’, ‘i’)

// constructor having the first argument as a regular expression literal
let reg = new RegExp(/pq+r/, ‘i’)

Frequently Asked Questions

What kinds of things can Ruby be used for?

Ruby is a multi-purpose programming language that may be used for various tasks. Ruby is an excellent language for creating static webpages, desktop programs, data processing services, and even automation solutions. It's used for web servers, DevOps, web scraping, and crawling, among other things.

Why should you learn the Ruby programming language?

Ruby is a programming language intended to increase programmer efficiency while still being enjoyable. Ruby is popular among programmers because it is high-level and has a straightforward syntax. You have less code to write and can focus on finding a solution to your problem.

What is the difference between Ruby and Python?

Ruby is a procedural language that may be disguised as an OO language. There are no functions and only the method calls while python is a cross-platform programming language. It has procedural programming functions as well as object-oriented programming objects.

What is the result of a regex match?

Match(String) returns the first substring in an input string that matches a regular expression pattern.

What is the definition of a regex pattern?

Regex (Regular Expression) is a pattern (or filter) that describes a set of strings that match the pattern.

Conclusion

Regular expressions are fantastic, but they can be a little challenging at times. You can design your ruby Regex more dynamically by using a tool like rubular.com. It's now your turn to fire up that editor and get coding!

You can also refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Ruby-related topics such as 8 reasons why Ruby should be your first language, everything you wished you knew about Ruby on RailsRuby on Rails for your next web development projectcareer opportunities after mastering Ruby on RailsRuby vs. Python, and many more!

Do upvote our blog to help our other ninjas to grow!

Happy reading!!

Live masterclass