Book Image

Comprehensive Ruby Programming

By : Jordan Hudgens
Book Image

Comprehensive Ruby Programming

By: Jordan Hudgens

Overview of this book

Ruby is a powerful, general-purpose programming language that can be applied to any task. Whether you are an experienced developer who wants to learn a new language or you are new to programming, this book is your comprehensive Ruby coding guide. Starting with the foundational principles, such as syntax, and scaling up to advanced topics such as big data analysis, this book will give you all of the tools you need to be a professional Ruby developer. A few of the key topics are: object-oriented programming, built-in Ruby methods, core programming skills, and an introduction to the Ruby on Rails and Sinatra web frameworks. You will also build 10 practical Ruby programs. Created by an experienced Ruby developer, this book has been written to ensure it focuses on the skills you will need to be a professional Ruby developer. After you have read this book, you will be ready to start building real-world Ruby projects.
Table of Contents (20 chapters)

How to validate an IP address using regular expressions

Now we'll build an IP matcher using Ruby and regular expressions. An example of how this could be used would be through building a security module that either verifies or blocks IP addresses in a program.

To do this, let's define a constant that will store the regular expression:

IP_ADDRESS_REGEX = /^((?:(?:^|\.)(?:\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])){4})$/ 

This regular expression will take all the valid IP address values, which range from 172.16.0.0 to 172.31.255.255.

The rest of the code is going to be fairly similar to the validator email address:

def is_valid_ip_address? ip
ip =~ IP_ADDRESS_REGEX
end

Next, let's check some use cases:

p is_valid_ip_address? ("999.16.0.0") ? "Valid" : "Invalid"
p is_valid_ip_address? ("172.16.0.0") ? "Valid" : "Invalid...