DEV Community

Cover image for Ruby Tutorial for Python Programmers: how to make the switch
Amanda Fawcett for Educative

Posted on • Originally published at educative.io

Ruby Tutorial for Python Programmers: how to make the switch

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

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 for Ruby or Django 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 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) 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.

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

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.

puts "Hello World!"
Enter fullscreen mode Exit fullscreen mode

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:

"Hello World"
Enter fullscreen mode Exit fullscreen mode

You will get the following:

irb(main):001:0> "Hello World"
=> "Hello World"
Enter fullscreen mode Exit fullscreen mode

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

irb(main):002:0> puts "Hello World"
Hello World
=> nil
Enter fullscreen mode Exit fullscreen mode

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

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.

Variable Assignment

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

puts number = 1
Enter fullscreen mode Exit fullscreen mode

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)

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

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 +.

puts "snow" + "ball"
Enter fullscreen mode Exit fullscreen mode

Output: snowball

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

puts "Ruby" * 3
Enter fullscreen mode Exit fullscreen mode

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

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.

{ "one" => "eins", "two" => "zwei", "three" => "drei" }
Enter fullscreen mode Exit fullscreen mode

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)

Array

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

[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

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:

puts ([1, 2, 3] & [2, 3, 4])
Enter fullscreen mode Exit fullscreen mode

Output: 2 3

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

Commenting

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

# Single line comment
Enter fullscreen mode Exit fullscreen mode
# Multiple
# Lines
Enter fullscreen mode Exit fullscreen mode
=begin
Block fashion
Commenting
=end
Enter fullscreen mode Exit fullscreen mode

Methods

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

def method_name
# Statement 
# Statement 
.
.
end
Enter fullscreen mode Exit fullscreen mode

We pass parameters to our methods in parentheses.

def method_name(var1, var2, var3)
# Statement 
# Statement 
.
.
end
Enter fullscreen mode Exit fullscreen mode

Classes

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

class Class_name

end
Enter fullscreen mode Exit fullscreen mode

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

In Ruby, objects are created with the new method.

object_name = Class_name.new
Enter fullscreen mode Exit fullscreen mode

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.

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
Enter fullscreen mode Exit fullscreen mode

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:

number = 5

if number.odd?
  puts "The number is odd."
end
Enter fullscreen mode Exit fullscreen mode

As this instead:

number = 5
puts "The number is odd." if number.odd?
Enter fullscreen mode Exit fullscreen mode

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. 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!

Continue reading about Ruby

Top comments (2)

Collapse
 
codeandclay profile image
Oliver

What do you mean by 'cannot modify built-in classes' in Ruby? You can monkey-patch any class in Ruby. What could 'modifying' do that monkey-patching can't?

Collapse
 
djuber profile image
Daniel Uber

I agree - as a concrete example, ActiveSupport adds days to Numbers (or maybe just to integers) so you can say things like 3.days.ago and get and answer that's the same as Time.now - 72.hours (hours is another patch on numbers to handle the conversion).

I suspect that might just have been a typo? I'm not familiar enough with Python to say if it's just those two columns are transposed. Can you modify/override List's __getitem__ in python to change how element access by offset works?