Home Web Development From PHP to Ruby on Rails

From PHP to Ruby on Rails

By Bernard Pineda
books-svg-icon Book
eBook $29.99
Print $36.99
Subscription $15.99
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99
Print $36.99
Subscription $15.99
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Understanding the Ruby Mindset and Culture
About this book
Are you a PHP developer looking to take your first steps into the world of Ruby development? From PHP to Ruby on Rails will help you leverage your existing knowledge to gain expertise in Ruby on Rails. With a focus on bridging the gap between PHP and Ruby, this guide will help you develop the Ruby mindset, set up your local environment, grasp the syntax, master scripting, explore popular Ruby frameworks, and find out about libraries and gems. This book offers a unique take on Ruby from the perspective of a seasoned PHP developer who initially refused to learn other technologies, but never looked back after taking the leap. As such, it teaches with a language-agnostic approach that will help you feel at home in any programming language without learning everything from scratch. This approach will help you avoid common mistakes such as writing Ruby as if it were PHP and increase your understanding of the programming ecosystem as a whole. By the end of this book, you'll have gained a solid understanding of Ruby, its ecosystem, and how it compares to PHP, enabling you to build robust and scalable applications using Ruby on Rails.
Publication date:
December 2023
Publisher
Packt
Pages
244
ISBN
9781804610091

 

Understanding the Ruby Mindset and Culture

Ruby has had quite a history since its inception by Yukihiro Matsumoto. The adoption of the language by the community has, of course, influenced the direction in which Ruby has been focused. But, at its core, Ruby has been very straightforward in the way you can and the way you should write programs/scripts with it. Every language has its own peculiarities, which the community takes to define what a good practice is and what is considered “bad” code. While this may be entirely subjective, this subjectiveness paves the way for what the author’s original intention for creating the language was into what the community wants the language to become.

Ruby was created with the idea of being extremely easy to read, flexible, and object-oriented. The same can be said about the technologies that came to pass because of Ruby. I’m talking about frameworks created in Ruby, such as Ruby on Rails (https://rubyonrails.org) and Sinatra (http://sinatrarb.com/). But I’m also talking about other tools that were created with that same mindset, such as Chef (https://www.chef.io/). All of these tools have common traits but the trait that stands out the most is readability. Once you’re in the Ruby “realm,” you’re able to read and understand code made for vanilla Ruby, a Ruby on Rails application API, or even a Chef recipe to manage and configure infrastructure. Ruby does not automatically make your code more understandable or readable, but it goes a long way to give you the tools to make your code easier to read. Making your code understandable is key to focusing more on the business (or hobby) at hand and focusing less on trying to understand what some code is doing.

But before we get there, we will need to make the switch to the Ruby mindset. In this chapter, we will start our journey into this mindset by covering the following topics:

  • Creating readable Ruby code
  • Object-oriented Ruby
  • Writing Ruby-esque code

You made up your mind to learn a new programming language. Congratulations! I, for one, would like to applaud this decision and hope it took you less time than it took me to be seriously curious about another programming language. I was a bit stubborn and reluctant at first, seeing every single downside of Ruby. My favorite phrase was, “I can do that in PHP easier.” But then, one day, it simply clicked and I never went back. Ruby has been my go-to language for a long time now. And I won´t try to oversell this to you. I refuse to say that Ruby is the best programming language there is because that would be answering a loaded question. There is no programming language that is universally better than the rest. What I can do is try to show you why I love Ruby.

 

Technical requirements

To follow along with this book, you will need:

  • Git client
  • rbenv (Ruby version manager to enable multiple versions of Ruby)
  • Ruby (versions 2.6.10 and 3.0 or above)
  • Any IDE of your choice installed to edit code (Sublime, Visual Studio Code, vim, Emacs, Rubymine, etc.)

All code examples have been written to work with Ruby versions 2.6.10 and 3.0 (or above). Some of the examples will need previous versions of Ruby (i.e. 2.6.10) to work with previous versions of Ruby on Rails (e.g. Ruby on Rails 5), but to guarantee that they work the same way as in this chapter, you should try to install the latest version of Ruby. You may get the installer for different operating systems here: https://www.ruby-lang.org/en/downloads/.

Additionally, to be able to use different versions of Ruby, I would also suggest you install rbenv from this GitHub repository: https://github.com/rbenv/rbenv.

The code presented in this book is available at https://github.com/PacktPublishing/From-PHP-to-Ruby-on-Rails.

 

Ruby is meant to be read as sentences

Having said all that about Ruby, let’s get our hands dirty and start with the most basic of concepts. You already know about PHP variables. Variables hold information that can be used and referenced in our program. Also, PHP is a dynamically typed language, which means that the PHP “engine,” which interprets our PHP code, will automatically infer the type of content within that variable. That’s to say the following two things:

  • We don’t have to define what type of content our variable has
  • A variable can change types without failing

Coming from PHP, you won’t have to break your head to learn a new way of using or defining variables with Ruby, as Ruby behaves exactly the same way. However, beware that in other languages that are strongly typed, such as Java, a variable has to be defined with the type that it will contain and it can’t change types over time.

So let’s play around with some variables in PHP:

<?php
$name = "bernard";
$age = 40;
$height_in_cms = 177.5;
$chocolate_allergy = true;
$travel_bucket_list = ["Turkey", "Japan", "Canada"];

Ruby is not much different in this scenario:

name = "bernard";
age = 40;
height_in_cms = 177.5;
chocolate_allergy = true;
travel_bucket_list = ["Turkey", "Japan", "Canada"];

For those experienced PHP developers reading this whose eyes might be bleeding from my lack of using PHP Standard Recommendation (PSR) standards on the PHP block, I apologize, but I wanted to give you a glimpse of how the code could be written in a similar manner rather than focusing on PHP’s best practices. Notice that we just wrote the variable names without the $ symbol. Another difference between PHP and Ruby is that we do not use any tag to denote PHP code, whereas, in PHP, we use the opening PHP tags (<?php). So, the main differences (so far) between our snippets are the way we call PHP code with the PHP tags and the way we refer to variables. While this is a functioning Ruby code, I intentionally wrote the Ruby block very PHP-esque to also give you all a glimpse of Ruby’s flexibility. Ruby is extremely flexible to the point of being able to bend Ruby’s own behavior. An example of this flexibility is that while we can add a semicolon (;) at the end of each line, it is a Ruby best practice to leave them out. Should this topic of Ruby’s flexibility interest you, you may want to check metaprogramming in Ruby. This Ruby guide is a great starting point:

https://www.rubyguides.com/2016/04/metaprogramming-in-the-wild/

But let’s not get ahead of ourselves, as this topic is really a complex one – at least for a beginner Ruby programmer.

Given the preceding code in PHP, let´s now determine whether the name is empty. In PHP, you would use the empty internal function. We surround it with another internal function called var_dump to show the contents of the empty function result:

$name = "Bernard";
var_dump( empty($name) );

This will output the following:

bool(false)

According to the documentation of the empty function, this is false because the name is not an empty string. Now, let’s try that in Ruby:

name = "bernard";
puts name.empty?;

There are a couple of things that we have to notice here. The first thing that comes to mind is that this is read almost as a sentence. This is one of the key points to how the Ruby community has come together and used Ruby to make code that is read by humans. For the most part, you should avoid writing comments on your code unless it’s for copyright and/or it does require an explanation. Ruby goes as far as having a strange way to write multiline comments. If I were to write a multiline comment on my code, I would have to look the syntax up because I’ve never used that notation. That’s not to say that you can’t or that you shouldn’t. It’s there for a reason. It simply means that the Ruby community seldom uses that notation. To write a comment in Ruby, you would simply add the hashtag symbol (#) as the first character on a line:

# This is a comment

As you know from comments within a snippet of code, this line will be ignored by Ruby. Keep in mind that a programming language, just like a spoken language, evolves due to its use. The best of tools may be lost just because no one uses them. Part of learning a language also involves learning the usage of the tools and best practices. This includes knowing what the Ruby community has decided not to exploit and what to use. So, while the community rarely uses multiline comments, all Ruby developers will take advantage of one of its most powerful tools: objects.

 

Everything is an object

The second thing that came to my mind while reading the previous code is that we are calling a method on a string. Now, let’s step back a bit, and this is where we start looking at code through our newbie set of Ruby eyes. Our variable name contains a string. Does this mean that our name is an object? Well, the short answer is Yes. Almost everything in Ruby is an object. I know this might seem as if we’re skipping a few chapters, but bear with me. We will see Ruby’s object-oriented syntax in Chapter 5. For now, let’s take this a step further within our code by getting what type of object our variable has with the following line:

puts name.class();

This will return the type of class of our object (in this specific case, String). We are able to do the same with the rest of our variables and we would get similar values (Integer, Float, TrueClass, or Array). And to take this even further to prove my point that almost everything in Ruby is an object, let’s read the following example:

puts "benjamin".class();

This will also return a String type. So, bear that in mind when you’re writing Ruby code. Now, let’s go back to the initial example with the empty function:

name = "bernard";
puts name.empty?();

The third thing we also notice is that we are actually asking a question. This baffled me the first time I saw it. How do you know when to ask? Is Ruby so intuitive that you can actually ask questions? What type of sorcery is this? Unfortunately, the truth is far less ominous than the code itself. In Ruby, we can name a function or a method with the question mark symbol as part of the name, solely to improve readability. It does not have any special execution or meaning to the Ruby interpreter. We are just able to name a method/function like that. Having said that, by convention, Ruby developers use the question mark to hint that we will return a Boolean value. In this case, it merely answers the question about the emptiness of the variable name. Simply put, if the name is empty, the question will return a true value, and vice versa. This naming technique is part of the Ruby philosophy to make our whole code readable. Additionally, this type of code style is permeated throughout many of Ruby’s internal classes. Some methods that are attached to number objects and array objects are an example of this. Here are a few examples:

  • .odd?
  • .even?
  • .include?

All these examples were named like that for the sole purpose of readability and nothing more. Some of them are even shared between different classes but have their own implementation for each type. While we are currently looking at the question mark symbol, let’s take a peek at a similar symbol: the exclamation point (!). Also known as a bang, it has a slightly different connotation within Ruby developers. Let’s look at it with an example.

Let’s show the name in uppercase letters. In PHP, we would write the following:

$name = "bernard";
echo strtoupper($name);

In Ruby, the same can be accomplished with the following code:

name = "bernard";
puts(name.upcase());

In both cases, this will return the name in uppercase (BERNARD). However, if we make any additional references to the name variable, the variable will remain unchanged:

name = "bernard";
puts(name.upcase());
puts(name);

This would return the following:

BERNARD
bernard

But what happens if we add the bang symbol (!)?

name = "bernard";
puts(name.upcase!());
puts(name);

This will return the name in uppercase twice:

BERNARD
BERNARD

The bang symbol in fact modifies the variable contents permanently. Functions that are named with the bang symbol are referred to as destructive methods because they modify or mutate the original object rather than just return the modified value. Examples of this are these methods from the String and Array classes:

  • .downcase!
  • .reverse!
  • .strip!
  • .flatten!

We can infer what they do just from reading them, but we now know what the bang symbol means in this context. Be careful when using these, but also don’t be shy of using them when the use case requires it. Now, when you read Ruby code, you will be aware of the question mark (?) and the bang (!) symbol.

 

Transitioning to Ruby

So far, we’ve seen examples in which our code looks very similar to PHP. As I mentioned before, I purposely did this to showcase the flexibility of Ruby. This makes the change to Ruby easier than other languages in which the syntax is a lot different than Ruby. However, this is only the beginning of our journey to becoming a Ruby developer. If we want to be able to read and write Ruby code and snippets like seasoned Ruby developers, we will need to see how the community has come to make Ruby code. In short, while we can write our code similar to other languages, we should avoid this practice and, in the process, learn about what Ruby has to offer to make our code more and more readable.

The first step we are going to take toward this goal is to remove unnecessary syntax within our code. To do this, we also must understand the utility of what we are removing.

Let’s take for an example our original code:

name = "bernard";
age = 40;
height_in_cms = 177.5;
chocolate_allergy = true;
travel_bucket_list = ["Turkey", "Japan", "Canada"];

In Ruby, the semicolon can be useful to separate multiline code into a single line dividing each line with a semicolon. If we took the name and the example to turn it into uppercase, we would have the following:

name = "bernard"; name.upcase!(); puts(name);

And this works perfectly fine. But remember, we are trying to make our code more readable. This is not more readable. It’s the opposite. And, if we are not going to write our whole code in a single line, then let’s take the original snippet (in multiple lines), and remove every single semicolon. This is starting to look more like Ruby:

name = "bernard"
age = 40
height_in_cms = 177.5
chocolate_allergy = true
travel_bucket_list = ["Turkey", "Japan", "Canada"]

This certainly seems to improve readability slightly by removing unused characters, but we are not finished. Let’s put this into practice with another example. Let’s write an example that will print out the string This person is allergic to chocolate if the value of the $chocolate_allergy variable is set to true. Because of our background in PHP, we might be compelled to write something similar to PHP. In PHP, we would write the following:

$chocolate_allergy = true;
if($chocolate_ allergy)
{
  echo "This person is allergic to chocolate";
}

With this in mind, we would write the following in Ruby:

chocolate_allergy = true
if(chocolate_allergy)
  puts("This person is allergic to chocolate")
end

This works fine, but it still looks a lot like PHP. An intermediate Ruby developer would most likely write something like this:

chocolate_allergy = true
puts "This person is allergic to chocolate"
  if chocolate_allergy

This is getting more and more readable by the second. But it also brings a couple of new practices to the table. For starters, the puts sentence is not surrounded by parenthesis. This is because, in Ruby, the use of parenthesis is optional for functions and methods. This is extremely useful as it’s starting to read like plain English. It works with functions with multiple arguments, too. As an example, an implemented function could very well look like this:

add_locations "location 1", "location 2"

Of course, this becomes cumbersome if we need to call nested functions. Let’s take this example with two functions:

def concatenate( text1, text2 )
  puts text1 + " " + text2
end
def to_upper( text )
  return text.upcase()
end

The concatenate function takes two strings and prints out both strings joined with a space between them. The second function just turns the input string into an uppercase string and returns the value. And this is where it could become problematic if we failed to use the parenthesis. If we wanted to concatenate the two strings and turn each string into an uppercase string, we could try the following:

concatenate to_upper "something", to_upper "else"

But we would fail miserably because the Ruby interpreter doesn’t know that "something" is the argument for the to_upper function. We can easily fix this with parenthesis:

concatenate to_upper("something"), to_upper("else")

Be careful with this knowledge as, like everything else, if overdone, it can be detrimental to our code’s readability. There are two additional points that we need to consider while deciding whether to use parenthesis. The first is that these rules also apply to the definition of the function. So, the concatenate function can be defined like this:

def concatenate text1, text2
  puts text1 + " " + text2
end

The second point is that the rule also applies to functions with no arguments – that is, we may remove the parenthesis from them, too. Let’s take the following as an example:

return text.upcase()

This will now become the following:

return text.upcase

More importantly, the use of methods that use the question mark and destructive methods (!) now make perfect sense for readability.

Let’s look at the following:

name.empty?()

This becomes as follows:

name.empty?

As another example, let’s take the following:

name.upcase!()

This now becomes as follows:

name.upcase!

The last point we will look at now is related to how Ruby behaves with the return of values. While a method can explicitly return a value with the return keyword, Ruby doesn’t need this keyword. Within functions and methods, Ruby automatically returns the last value that is referenced. Let’s use the following example for this:

def to_upper text
  return text.upcase
end

That example would turn into this:

def to_upper text
  text.upcase
end

You will see a lot of Ruby code like this. It can be intimidating and confusing at first, but once you understand what Ruby is doing, it simply starts to make more sense.

As you have probably realized by now, Ruby’s creator put a lot of emphasis on these tools to make it easier to write readable code. The community adopted this ideology and put it into practice. We not only see code using these conventions and rules to increment readability but we also see Ruby programmers adopt other conventions that, while they are not part of the Ruby rules per se, make perfect sense when used in context. I’m referring to variable and method naming. Because Ruby developers will try to make their code read like plain English, they will spend a lot of time thinking about how to name methods and variables to make the code more readable. For this reason, snake-case is more often used in Ruby, as it helps with readability. With that in mind, let’s look at this example:

chocolate_allergy = true
puts "This person is allergic to chocolate"
  if chocolate_allergy

We can still improve its readability. And it wouldn’t just be a syntactic change; it would also involve variable names and even defining a method, just to improve readability. So, a seasoned Ruby developer might write the final snippet for this example as follows:

def say text
  text
end
is_allergic = true
say "This person is allergic to chocolate" if is_allergic

As you can see, Ruby developers will go very far to make the code as readable as plain English. Of course, this is not always feasible and sometimes it’s not practical as it at times requires putting a lot of effort into writing even something simple, but for the most part, as long as it’s readable, by following these guidelines, other developers will thank you, not just the Ruby ones.

 

Summary

In this chapter, we covered the syntactic differences and similarities between PHP and Ruby, Ruby’s tools for readability, and Ruby’s syntactic flexibility. We also learned about the question mark (?) and the exclamation or bang symbol (!). Making it this far means that you are indeed trying to reuse your previous programming skills but with a new language: Ruby. This is a great start because you can skip one of the most difficult parts of learning a new language from scratch: the logical part. And while we’ve only seen the surface of Ruby, more importantly, we got a clear glimpse of how Ruby developers think when they’re writing code. We learned that to a Ruby developer, readability comes first. We not only use syntax and language constructs to make this possible but we also use objects to increase the code’s legibleness. The more it reads like a sentence, the better. We looked at some simple examples of Ruby, and while you could follow along, it was not the purpose of the exercise. It was more to pique your interest.

To move along on this learning path, we now need the proper tools to start writing and running Ruby code. In the next chapter, we will look at the different ways to install Ruby and set up our local environment so that we can start learning real examples of Ruby, and eventually follow along in the process.

About the Author
  • Bernard Pineda

    Bernard Pineda is a seasoned developer with 20 years of web development experience. Proficient in PHP, Ruby, Python, and other backend technologies, he has taught PHP and PHP-based frameworks through video courses on platforms like LinkedIn Learning. His extensive work with Ruby and Ruby on Rails, along with curiosity in frontend development and game development, bring a diverse perspective to this book. Currently working as a Site Reliability Engineer in Silicon Valley, Bernard is always seeking new adventures.

    Browse publications by this author
Latest Reviews (1 reviews total)
It was a decend read but the rails version is outdated but the code worked ok.
From PHP to Ruby on Rails
Unlock this book and the full library FREE for 7 days
Start now