Ruby Tutorial for Python Programmers: how to make the switch
Tags: ruby, python, languages, functional
Published: 2021-04-20 16:52:40

Ruby is a general-purpose, dynamic, open source programming language that focuses on **simplicity and productivity**. The Ruby programming language is frequently compared to Python for their similarities. Many developers say that learning Ruby is easier if you know Python due to their similarities. However, these two languages differ in major ways.

We've created this basic introduction to help you make the transition from Python to Ruby. We'll go over their main differences and then take a dive into Ruby's syntax so you can get hands-on with Ruby code quickly. 

**Here's what we'll cover today:**

* [Ruby vs Python](#vs)
* [Summary of Main Code Differences](#differences)
* [Hello World with Ruby](#hello)
* [Ruby Syntax Quick Guide](#syntax)
* [What to learn next with Ruby](#next)

<a name="vs"></a>

## Ruby vs Python

Ruby and Python are both popular programming languages known for their speed, simplicity, and user-friendly syntax. Both languages are flexible, object-oriented , dynamic, and have a lot of useful frameworks and libraries to use, particularly for web applications and web development *([Ruby on Rails](https://www.educative.io/blog/ruby-on-rails) for Ruby or [Django](https://www.educative.io/blog) for Python)*. 

**Ruby** is a high-level, interpreted programming language, created in 1995 by Yukihiro Matsumoto. His goal was to make an object-oriented scripting language that improved on other scripting languages of the time. 

Ruby also allows for [functional programming](https://www.educative.io/blog/what-is-functional-programming-python-js-java) and is known for being very similar to written human languages, making it easy to learn.

**Python** is an interpreted, high-level general-purpose language, created by Guido van Rossum with the goal of code readability. Python is know well-loved for its robust standard library.


| **Ruby**                                                                                                       	| **Python**                                              	|
|------------------------------------------------------------------------------------------------------------	|-----------------------------------------------------	|
| No primitive data types. Everything is an object.                                                          	| Has primitive types and objects                     	|
| Mixins can be used                                                                                         	| Mixins cannot be used                               	|
| Less available functions. Relies mostly on methods.                                                        	| Lots of available functions                          	|
| Cannot modify built-in classes                                                                             	| Can modify built-in classes                         	|
| Supports Tuples with Rinda. Other collections include Arrays, Hash, Set, and Struct. 	| Supports Tuples, Sets, Dictionary (Hash), and Lists 	|
| Iterators less common                                                                                      	| Iterators are very common                           	|

#### Career

Both languages are used by big companies. Companies that use Python include YouTube, Instagram, Spotify, Reddit, Dropbox, while Ruby is used at Hulu, Basecamp, GitHub, and Airbnb. Ruby developers also tend to make higher salaries than Python developers. StackOverflow's 2020 survey lists Ruby's global average salary at $71k and Python's at $59k. 

> Both Ruby and Python offer higher annual salaries than other software development languages, including PHP, JavaScript, and Java.  


#### Machine Learning

Python is currently the go-to language for machine learning (ML) and artificial intelligence (AI) due to its extensive libraries and visualization tools. Ruby does offer some competitive options, but there is a long way to go before it will hold a torch to Python. So, if you are looking to work in data science, Python is the winner.


#### Web Frameworks

The main web frameworks for both Ruby and Python, Django and Ruby on Rails, are rather similar. Both are based on the classic [model-view-controller (MVC)](https://www.educative.io/blog/mvc-tutorial) pattern, and they both provide similar  repositories (PyPi for Python and RubyGems for Ruby). Both frameworks perform well and are easy to learn.


#### Testing Environment

Test-driven development (TDD) is pretty standard for both Ruby and Python, but Ruby does offer **behavior-driven development (BDD)** while Python does not, which may be useful in some cases


#### Community

Both languages have large, active communities, which Python's community being a bit larger, namely because Ruby is most popular for its development tool Ruby on Rails. Both communities seem to be equally active and supportive. 

One benefit to Ruby is that there are unique Ruby forums and job boards since the language is more specialized in some regards.

<br>

<a name="differences"></a>


## Summary of Main Code Differences 

Now that we understand the difference between Ruby and Python at a high level, let's dive into the main code differences between the two. We've compiled the main things that differ from Python below. 

**In the Ruby programming language:**
* Strings are mutable
* You can make constants 
* Parentheses for most method calls are optional
* There’s only one mutable list container (Array)
* There are no “new style” or “old style” classes 
* Only `false` and `nil` evaluate to false, and everything else is `true`
* You never directly access attributes. Instead, we use method calls.
* We use `elsif` instead of `elif`
* We use `require` instead of `import`
* We use mixins instead of multiple inheritance
* `yield` executes another function that is passed as the final argument, then it resumes
* We use `public`, `private`, and `protected` for access 

<br>

<a name="hello"></a>

## Hello World with Ruby

Now that we understand how Ruby and Python differ at the code level, let's look at some actual Ruby code, starting with the classic Hello World program.  Take a look below and note how simply Ruby's syntax is here.

```ruby
puts "Hello World!"
```

Here, the `puts` keyword is used to print. Remember: Ruby's code is very readable, designed to emulate spoken English language. 

There's even a simpler way to do this. Ruby comes with a built-in program that will show the results of any statements you feed it, called **Interactive Ruby (IRB)**. This is the best way to learn Ruby. First, open IRB:

* **macOS:** open Terminal and type `irb`. Hit enter.
* **Linux:** open up a shel, type `irb`, and hit enter.
* **Windows:** open Interactive Ruby from the Start Menu (see the Ruby section)

If you type:

```ruby
"Hello World"
```

You will get the following:

```ruby
irb(main):001:0> "Hello World"
=> "Hello World"
```

The second line tells us the result of the last expression. We can print this using the `puts` command we learned before.

```ruby
irb(main):002:0> puts "Hello World"
Hello World
=> nil
```

Here,  `=> nil` is the result of the expression, since `puts` always returns `nil`.

<br>

<a name="syntax"></a>


## Ruby Syntax Quick Guide

Let's now quickly go over the basics of Ruby's syntax that may be different from what you're used to in Python. Note how Ruby differs and how it is similar as you read.

<br>

### Variable Assignment

In Ruby, you assign a name to a variable using the assignment operator `=`, like so:

```ruby
puts number = 1
```

Here is a list of the different kinds of variables in Ruby:
* Local variables (`something`)
* Instance variables (`@something`)
* Constants (`Something` or `SOMETHING`)
* Global variables (`$something`)

<br>

### Identifiers and Keywords

Keywords and identifiers are similar to Python. Identifiers are case sensitive, and they may consist of alphanumeric characters and underscore `_`.

Ruby's reserved keywords include the following:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yeeemt0x8roiywvf03u6.png)


### Strings
In Ruby, a string is a sequence of characters inside quotation marks `" "`. We can also use single quotation marks. 

You can concatenate strings with the plus sign `+`. 


```ruby
puts "snow" + "ball"
```

**Output:** snowball


In Ruby, multiplying a String by a number will repeat a String that many times.

```ruby
puts "Ruby" * 3
```

**Output:** RubyRubyRuby


Some important methods for Ruby strings include: 
* `size`
* `empty?`
* `include?`
* `gsub`
* `split`

> **Pro Tip:** Ruby's percentage sign `%` shortcut can be used with strings and arrays
>
> * `%w` will create an array of strings
>
> * `%i` with create an array of symbols
>
> * `%q` will create a string without quotation marks


<br>

### Hashes

In Ruby, you can create a Hash by assigning a key to a value with `=>`. We separate these key/value pairs with commas and enclose the whole thing with curly braces.

```ruby
{ "one" => "eins", "two" => "zwei", "three" => "drei" }
```
This defines a Hash with three key/value pairs, so we can look up three values (the strings `"eins"`, `"zwei"`, and `"drei"`) using three different keys (the strings `"one"`, `"two"`, and `"three"`).

Some important methods for Ruby hashes include:
* `key?`
* `fetch`
* `merge`
* `new` *(for default values)*

<br>

### Array

In Ruby, we create an Array by separating values with commas and enclosing this list with square brackets, like so:

```ruby
[1, 2, 3]
```

> **Note:** Ruby Arrays always keep their order

Like in Python, there are all sorts of things you can do with Arrays. The most important methods being:
* `size`
* `empty?`
* `push` / `pop`
* `join`
* `flatten`

Here is an example of the intersection operator `&`, which finds the intersecting parts of our arrays:


```ruby
puts ([1, 2, 3] & [2, 3, 4])
```

**Output:** 2 3

<br>

### Parenthesis
In Ruby, parenthesis and semicolons are not required, but we can use them. However, we follow these basic rules:

* Do use parenthesis with method arguments: `def foo(a, b, c)`
* Do use parenthesis to change the priority of an operation: `(a.size + b.size) * 2`
* Don't use parenthesis when defining a method that has no arguments: `def foo`

<br>

#### Commenting 

There are three main ways we can add comments to a Ruby program.

```ruby
# Single line comment
``` 

```ruby
# Multiple
# Lines
```

```ruby
=begin
Block fashion
Commenting
=end
```

<Br>

### Methods 

In Ruby, we define methods using the `def` keyword followed by `method_name`. IT ends with the `end` keyword. 

```ruby
def method_name
# Statement 
# Statement 
.
.
end
```

We pass parameters to our methods in parentheses. 

```ruby
def method_name(var1, var2, var3)
# Statement 
# Statement 
.
.
end
```
<Br>

### Classes
In Ruby, we create classes using the `class` keyword followed by the name of the class. 

```ruby
class Class_name

end
```

> **Note:** The first letter of your class names should be a capital letter.

In Ruby, objects are created with the `new` method.

```ruby
object_name = Class_name.new
```

<br>

### Conditionals 

Conditional statements are similar to most other languages with a few slight differences. Take a look at the examples below to get at sense of how they look in Ruby.

```ruby
number = 5

if number.between?(1, 10)
  puts "The number is between 1 and 10"
elsif number.between?(11, 20)
  puts "The number is between 11 and 20"
else
  puts "The number is bigger than 20"
end
```

**Output:** The number is between 1 and 10



> **Note:** The `elsif` and `else` statements are optional. You can have an `if` statement without `elsif` or `else` branches, an `if` statement only with an `else`, or you could have an `if` statement with one or more `elsif` statements. 

Ruby also has a shorthand for working with conditional statements. So, we could write this bit of code:

```ruby
number = 5

if number.odd?
  puts "The number is odd."
end
``` 

As this instead: 

```ruby
number = 5
puts "The number is odd." if number.odd?
```

<br>

<a name="next"></a>

## What to learn next with Ruby

Now that you know the basics of Ruby and know how it differs from Python, you're ready to cover more advanced topics. We recommended studying the following concepts next:
* Ruby inheritance
* Using Ruby libraries
* Nested arrays 
* Ruby blocks

To get started with these concepts and get hands-on with Ruby, check out Educative's course **[Learn Ruby from Scratch.](https://www.educative.io/courses/learn-ruby-from-scratch)** This introductory course offers tons of hands-on practice on all the need-to-know topics, including variables, built-in classes, objects, conditionals, blocks and much more!

By the end, you'll be a confident Ruby developer, ready to take on complex projects!

*Happy learning!*

<br>

### Continue reading about Ruby 
* [8 tricks and best practices for improving your Ruby code
](https://www.educative.io/blog/ruby-best-practices)
* [Getting Started with Ruby on Rails: build a web app with Ruby](https://www.educative.io/blog/ruby-on-rails)
* [Docker with Rails: Benefits and Top Use Cases](https://www.educative.io/blog/docker-with-rails)