A Beginner’s Guide To Ruby

One step closer to write your next big thing

Mahbub Zaman
May 30, 2020 · 8 min read
Photo by Max Duzij on Unsplash

an avid Android developer, I came across Ruby two years back, and since then, I have been enjoying it very much. In my previous workplace, I used it to build a Supporter Management System (SRM) for Not-for-profit organizations. On numerous occasions, I used it for my side projects to build my portfolio.

Why do you want to learn Ruby in the first place? Some benefits of Ruby are:

  • Write less: Spend less time on writing codes and more on solving problems.
  • Build fast: Framework like Ruby on Rails gives you the power to build in less time.
  • Deploy 🚀 for free: Use Heroku to test your application with others.
  • Community: Ruby User Groups, Ruby Meetup Groups will help you to learn and share knowledge 📚.

By the time you finish reading this tutorial, you’ll be able to use Ruby to write scripts to automate your daily work. Now let’s discuss some basic concepts and features of Ruby. First things first, make sure you have Ruby installed on your machine. In case you don’t want to install Ruby natively, you can use docker.

docker run -it --rm ruby:latest
# check which version of Ruby you're running
RUBY_VERSION
Ruby

Ruby is an object-oriented and interpreted (executes the code at runtime) programming language like Python. In Ruby, everything is an object.

1.next # 2

To test the above code, you can use IRB (interactive Ruby), it’s a tool to execute Ruby code read from the standard input interactively. Type the irb command from your shell to initiate the interpreter.

Now run this: puts (1.methods).sort

Comment

There are a couple of different ways to comment in Ruby. Like any coding language, it’s essential to annotate your code to explain the intent. It will help you to understand and debug your code in the future. Here are the different ways that work in Ruby:

# single line comment

=begin
multiline
comment
=end

I prefer # for multiline comments because it maintains my style guide and easier to read.

# begin
# multiline
# comment
# end

Data types

There are nine data types that you’ll use when you’re working in Ruby.

  1. Integer. e.g. id = 17
  2. Float. e.g. value = 68.23
  3. String. e.g. name = "Robert"
  4. Array. e.g. ids = [17, 18]
  5. Hash. e.g. person = {id: 17, name: "Robert"}
  6. Boolean. e.g. is_active = true
  7. Symbol. e.g. status = :green
  8. Range. e.g. dice = 1..6
  9. Nill. e.g. name = nil

Among these data types, Symbol and Range are quite distinctive compare to languages like Java and C#. It’s worth understanding them in greater detail so that you can use them to their full potential.

Symbol

Symbol objects represent names. Symbols are immutable, which means every symbol is unique, and we can’t change it. Referencing the same symbol multiple times is the same as referencing the same object everywhere in your program. As a result, we can save both time and memory by referencing the same memory location.

# symbols as hash keysweek_days = {red: 11, green: 22}

Range

Ranges allow us to declare data with a beginning and an end, it has two operators to generate ranges. For creating inclusive ranges, use ... For creating exclusive ranges, use .... It’s one of the coolest features in Ruby. For example, you can do the following to generate all the capital letters in English.

Example of inclusive and exclusive range.

Variables and Scope

There are five types of variables that you’ll use in Ruby. Each one has a different scope — that is, the existence of a variable.

1. Local variables begin with [a-z] or _. We must initialize a variable before usage.

count = 10 or _count = 10

Scope: The scope of a local variable is one of the following.

proc { ... }
loop { ... }
def ... end
class ... end
module ... end
the entire program (unless one of the above applies)

2. Instance variables begin with@. They have the nil value until we initialize them.

@id

Scope: Instance variable is distinct to each object of its class. We can’t access it outside the class. Use the keyword attr_reader for reading and attr_writer for writing instance variables. When we need both use the keyword attr_accessor. These reader and writer methods are also known as a getter, setter methods in other languages.

3. Class variables begin with @@. We must initialize a variable before usage.

@@name = []

Scope: The class variable is independent of any object of its class. We use ClassName.class_variable to access class variables from outside of the class.

4. Global variables begin with $. They have the nil value until we initialize them.

$version = "0.8.9"

Scope: A program can refer to a global variable from anywhere.

5. Constants begin with [A-Z]. We must initialize a variable before usage and outside of methods. Constants can change its value 😯, but you will get a warning, which you should avoid.

PI = 3.14
PI = 3.1416
# warning: already initialized constant PI
# warning: previous definition of PI was here

Scope: Accessible outside the class.

Conditional structures

Like any other programming language, conditional structures are used in Ruby to control the flow of the program depending on one or more boolean conditions, which can either evaluate to true or false.

If elsif else expression

The use of parentheses is optional.

unless expression

The unless statement is the opposite of if, evaluates when it’s false.

Shorthand

Ruby allows the shorthand notation of if and unless statements. It’s super useful when you have a single line to work with under if or unless.

Case Expressions

The case statement returns the value of the last expression executed.

Methods

A method is a function that takes zero or more parameters and returns a value. Ruby method returns nil by default.

Declaring a method

In Ruby, the last statement evaluated is the return value of that method. The return statement is optional. Depending on your preference, you can choose either of them 👍. I prefer to use the return statement because it's easier to understand.

Calling a method

In Ruby, you can call methods without parentheses.

Define a default value for a method parameter

When a method argument is missing, you can assign a default value for that parameter.

Use parameter for the default value

You can use a parameter as a default value for another parameter.

Pass a variable-length argument to a method parameter

When the number of method arguments is not fixed, you can use * before the parameter name to make it dynamic.

Boolean method

In ruby methods that end with a question mark (?) are called boolean methods, which either return true or false.

You can write your boolean methods as well 😎.

Class method

A class method is a class-level method, which means you call a class method on a class. There are many ways of defining a class method.

Here is the under the hood explanation, a class method is an instance method of the Class object. When we create a new class, an object of the type Class is initialized. It’s then assigned to a global constant, in this case, Mobile.

Blocks

Codes between do and end (for multiline) or curly brackets { and } (for a single line) are called blocks. They can have multiple arguments defined between two pipes (|arg1, arg2|). A block can be passed as a method parameter or can be associated with a method call. Block returns the last evaluated statement.

Methods can take blocks implicitly and explicitly. If you want to call a block implicitly use the yield keyword. Yield finds the block and calls the passed block. Since you can pass implicit blocks, you don’t have to call yield, and the block will be ignored.

There are two more ways to write blocks in Ruby: proc and lambda.

1. A proc is like a block, and we can store it in a variable. It returns from the current context.

p = Proc.new { puts "Hello World" }

def give_me_data(proc)
proc.call
end

give_me_data p
# output
# Hello World

2. Lambda behaves like proc but it returns from itself (like a method).

# there are multiple ways to declare a lambda
l = lambda { puts "Hello World" }
# shorthand
l = -> { puts "Hello World" }

# call the lambda
l.call

# output
# Hello World

# there are multiple ways you can call a lambda
l.()
l[]

Even though both of them look very similar, there are some differences. For example, proc supports arbitrary arguments, but lambda supports strict arguments. If the lambda requires one argument, but you provide two, it will throw an exception.

wrong number of arguments (given 2, expected 1)

Array

Use of the built-in method sort!

The ! is used after the method when you want to modify the object.

a = ["Drama",
"Mystery",
"Crime",
"Sci-fi",
"Disaster",
"Thriller"]
a.sort
puts a
# we didn't modify the object
# Drama
# Mystery
# Crime
# Sci-fi
# Disaster
# Thriller

There are many ways you can iterate an Array. We will discuss the use of each in detail.

Classes

When you create a new object, it looks for a method named initialize and executes it, like a constructor in Java. The attr_accessor acts as a getter and setter for an instance attribute.

Modules

We use Modules for combining similar methods so that other classes or modules can use it. One of the benefits of using a module is it provides a namespace and prevent name clashes. Read here for a detailed explanation. You can not instantiate a module (like abstract classes in Java ☕️).

module MyRandomHelper
def roll_dice
rand(1..6)
end
end

class Person
attr_accessor :name, :number
end

class Player < Person
include MyRandomHelper
attr_accessor :score
end

p = Player.new
p.roll_dice
Photo by Clark Tibbs on Unsplash

Wrap Up

Go ahead and write some cool scripts to automate your everyday work. It could be as simple as a random text generator or a web scraper. The simplicity of Ruby language is one of the reasons it’s so popular among startups. Startups can build applications faster using frameworks like Ruby on Rails and enter the market soon.

('a'..'z').to_a.sample(7).join("")

Here are some more examples of Ruby scripts. If you want to know more about Ruby, have a look into this cheat sheet. As a Ruby developer, I use Ruby for automating my daily repetitive tasks, and I’m keen to share that knowledge with others because it can help you save valuable time and effort.

The Startup

Get smarter at building your thing. Join The Startup’s +785K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Mahbub Zaman

Written by

Computer Engineer. One day I’ll write a book. https://linktr.ee/lifeparticle

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Mahbub Zaman

Written by

Computer Engineer. One day I’ll write a book. https://linktr.ee/lifeparticle

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +785K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store