Programming For Entrepreneurs - Ruby Crash Course

Learning Ruby

Before learning how to sprint, you should understand how to walk without falling all over yourself. Before diving into building your product, you are going to get a quick crash course or the Ruby Programming Language. Since this book is all about learning on the job, lets jump into learning Ruby in the Interactive Ruby tool (irb for short).

Starting a Ruby Environment

Now that you have Docker installed, it will be easy to start up a new environment. Open up your terminal application (Terminal on Mac, Command Prompt on Windows). On the command line, type:

docker run -it ruby:2.5 irb

It may take a few minutes to download the Ruby docker image, but once it’s finished you will see the irb interactive shell:

irb(main):001:0>

What did that command do? Lets break it down:

Hello Ruby

When learning any new programming language it’s customary to start with the “Hello World” example. To make sure everything is working, go ahead and type "Hello Ruby" in the interactive shell.

irb(main):001:0> "Hello Ruby"
=> "Hello Ruby"

Before you get too excited, you didn’t write the worlds smallest “Hello World” program. The irb will evaluate the last expression and return the result of it after the =>. In other words, the value of "Hello Ruby" is “Hello Ruby”. That makes sense, right?

To print out the words “Hello Ruby”, you need to add one more thing.

irb(main):002:0> puts "Hello Ruby"
Hello Ruby
=> nil

You now have 2 lines of output for the single line you put in. puts is our first Ruby command. It takes a Ruby object (or multiple objects) and prints it followed by a new line separator. When it evaluates, it prints the objects and returns nil.

What is nil? nil is a special Ruby object that represents nothing. For fun, lets see what happens when we try to puts the nil.

irb(main):003:0> puts nil

=> nil

Notice that it printed and empty line above the => nil return? That is because we printed nothing, which is an empty line.

Basic Calculator

Working with numbers is a common function when programming. Ruby provides built in operators for basic math problems. For instance, addition:

irb(main):004:0> 5 + 6
=> 11

Multiplication is as simple as:

irb(main):005:0> 5 * 5
=> 25

We can also represent 5*5 as 5 squared:

irb(main):006:0> 5 ** 2
=> 25

The ** operator is the Ruby way of saying to the power of. Can we go the opposite direction?

irb(main):007:0> Math.sqrt(25)
=> 5.0

Ok, probably not what you expected! There isn’t a builtin operator for square root, so you can use the Math module to solve the problem.

Variables

Performing math operations this way could become complicated if we want to do anything more advanced. Ruby provides a way to store the results of an expression to use later.

Lets use the Pythagorean Theorem to demonstrate how this works. Recall the theorem says that on a right triangle with 3 sides, a^2 + b^2 = c^2. You can use Ruby to solve for c.

irb(main):008:0> a = 3 ** 2
=> 9
irb(main):009:0> a
=> 9

Here you are storing the results of 3 ** 2 into a variable named a. If you type the name of the variable and hit enter, Ruby will spit out the value stored in it.

irb(main):008:0> b = 4 ** 2
=> 16
irb(main):009:0> b
=> 16

The last step is to use the two new variables to solve for c in the equation.

irb(main):010:0> c = Math.sqrt(a+b)
=> 5.0

To see the variables, print them:

irb(main):011:0> puts a, b, c
9
16
5.0
=> nil

Modules

Ruby comes with builtin modules to help solve common problems. A module is a way to group code by a topic. The Math module contains the square root method (more on this soon!), but it also contains other common math operations like sin() or cos().

To use a method contained in a Module, follow the pattern <Module>.<method>. Another important thing to notice is that the sqrt method always returns a float. Most of the time, when we take the square root of a number it will not be a nice integer.

Methods

Commonly, you will need to run a bit of code more than one time. In this case you can wrap it inside a method to make calling it easier. This is the same way the methods are defined inside the builtin modules like Math. Lets create a new method to print out “Hello Ruby” whenever we want.

irb(main):008:0> def hello
irb(main):009:0> puts "Hello Ruby"
irb(main):010:0> end
=> :hello

Walking through what is different:

The last line, => :hello means the method has registered with Ruby. Now you can use it:

irb(main):011:0> hello()
"Hello Ruby"
=> nil

You can also define the function to accept a name and print it instead of a static string.

irb(main):012:0> def hello(name)
irb(main):013:0> puts "Hello #{name}!"
irb(main):014:0> end
=> :hello

Now, when you call, include the name:

irb(main):015:0> hello("Everyone")
"Hello Everyone"
=> nil

What happens when you call hello without an argument?

irb(main):016:0> hello()
Traceback (most recent call last):
        3: from /usr/local/bin/irb:11:in '<main>'
        2: from (irb):18
        1: from (irb):14:in 'hello'
ArgumentError (wrong number of arguments (given 0, expected 1))

What just happened? This is how Ruby informs you an error has occurred. The final line tells you that the wrong number of arguments were passed to the hello method.

Is there a way to stop this from happening? You can provide a default value so this doesn’t happen.

irb(main):017:0> def hello(name = "World")
irb(main):018:0> puts "Hello #{name}!"
irb(main):019:0> end
=> :hello

If you run the empty method now, it won’t throw an error message.

irb(main):020:0> hello()
"Hello World!"
=> nil

Classes

Ruby is an Object-Oriented language. This means we use Objects to store private state information that other parts of the program can’t access directly. There’re other aspects of Object-Oriented, but this is the main concept we care about for now.

To build an object, Ruby first needs to have a template of what the object looks like. These templates are called Classes.

Lets create a Greeting system that says hello and goodbye to users.

irb(main):021:0> class Greeting
irb(main):022:1>   def initialize(name = "World")
irb(main):023:2>     @name = name
irb(main):024:2>   end
irb(main):025:1>   def say_hello
irb(main):026:2>     puts "Hello #{@name}!"
irb(main):027:2>   end
irb(main):028:1>   def say_goodbye
irb(main):029:2>     puts "Goodbye #{@name}, see you soon."
irb(main):030:2>   end
irb(main):031:1> end
=> :say_goodbye

Wow, that is a lot of code! If you notice, there are only 3 new concepts introduced though.

  1. Encapsulation - The Greeting class contains all of your methods, instead of them being defined globally.
  2. Instance Variables - There is now a variable that is being shared across multiple methods @name. The @ tells you it is an instance variable.
  3. Constructor - We need a way to initialize a class into an object, and in Ruby that is the initialize method.

After defining a class, you can now use it to create an Object.

irb(main):032:1> greeting = Greeting.new("Will")
=> #<Greeting:0x0000555e0c9ef998 @name="Will">
irb(main):033:0> greeting.say_hello
Hello Will!
=> nil

You can use the new method on an object and Ruby will automatically call the initialize method you defined with any arguments you pass.

Questions

These are the basic concepts of Ruby. This book will introduce more advanced concepts of the language as you need them, so make sure you understand these core concepts now!

If you have any questions or need help mastering these concepts, join us over on the mailing list! That will get you access to the community and we can help you with any concepts you struggle with!

The next chapter jumps straight into building a real application.

Table Of Contents

Want to learn more? Join our Virtual Boot Camp!