Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
From PHP to Ruby on Rails

You're reading from  From PHP to Ruby on Rails

Product type Book
Published in Dec 2023
Publisher Packt
ISBN-13 9781804610091
Pages 244 pages
Edition 1st Edition
Languages
Author (1):
Bernard Pineda Bernard Pineda
Profile icon Bernard Pineda

Table of Contents (15) Chapters

Preface 1. Part 1:From PHP to Ruby Basics
2. Chapter 1: Understanding the Ruby Mindset and Culture 3. Chapter 2: Setting Up Our Local Environment 4. Chapter 3: Comparing Basic Ruby Syntax to PHP 5. Chapter 4: Ruby Scripting versus PHP Scripting 6. Chapter 5: Libraries and Class Syntax 7. Chapter 6: Debugging Ruby 8. Part 2:Ruby and the Web
9. Chapter 7: Understanding Convention over Configuration 10. Chapter 8: Models, DBs, and Active Record 11. Chapter 9: Bringing It All Together 12. Chapter 10: Considerations for Hosting Rails Applications versus PHP Applications 13. Index 14. Other Books You May Enjoy

Ruby Scripting versus PHP Scripting

Just like the similarities we found when we looked at Ruby’s and PHP’s syntax, we are going to take things a step further and dive into the similarities between Ruby scripts and PHP scripts. A script is a piece of code that will run a task and then stop its execution. Said task may be simple or complex, but it is not considered an application as it stops once the task is done and only performs the task. Let’s take this step together and start writing simple scripts so that we can eventually write full-fledged applications.

With that in mind, in this chapter, we will cover the following topics:

  • Useful scripts
  • Text handling
  • File handling
  • Command-line arguments

Technical requirements

To follow along with this chapter, we will need the following:

  • Any IDE to view/edit code (for example, SublimeText, Visual Studio Code, Notepad++ Vim, Emacs, and so on)
  • For macOS users, you will also need to have XCode Command Line Tools installed
  • Ruby version 2.6 or later must be installed and ready to use

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

Beyond Hello World

In the previous chapter, we learned how to run (or execute) Ruby code. However, we only focused on the syntax and not the usefulness of the code. The famous Hello World script we write in any language is, by itself, useless, at least from a practical sense. So, let’s start learning how to use some tools to give our scripts a little bit of usefulness.

One useful tool in any language is having a way to verify the version of the programming language that we are currently using. Once we obtain the version, we can stop the execution if the version we are using is incorrect. So, our first step is to get the current Ruby version. Let’s create a file called version_verification.rb with the following code:

# version_verification.rb
puts "We are running Ruby version #{RUBY_VERSION}"

We can run this script on our shell by typing the following command:

ruby version_verifications.rb

It should output something similar to this:

We are running...

Text handling

You will most likely encounter strings (texts) in your journey to becoming a Ruby developer, so it’s important to know how to handle and manipulate this type of data. Whether you need to capitalize, get a partial string, or even trim a string, Ruby comes with a vast arsenal of tools to manipulate text as we see fit. Most programming languages have this type of tool, and Ruby is not an exception. As an example, let’s say we wanted to grab a previously entered name and make sure that all the letters were in uppercase or lowercase. Ruby has two methods to do exactly that: upcase() and downcase(). Let’s try them out by creating a file called string_cases.rb with the following code:

first_name = "benjamin"
last_name = "BECKER"
puts "My full name is #{first_name} #{last_name}"

So far, we’ve declared two variables and used interpolation to output the full name. Let’s say we were to run this script on the shell...

File manipulation

Some decades ago, one of the few options (if not the only option) for saving information was storing it in files. All sort of data was stored in these files: passwords, user data, config data, and more. Saving information in plain text files was, at the time, the most feasible option to save information. It all came to an end with the advent of databases (DBs) and DB usage. DBs became a more feasible and popular option, and they now came in different flavors. While this is still true today, using a DB comes with a quite expensive cost. I’m not only talking about a monetary cost – I’m talking about it in terms of memory, disk, and processing time. So, in certain use cases, it’s still a much better option to use plain text files to store information. To that purpose, most programming languages, including Ruby and PHP, make this task straightforward. Let’s take a look at how we can take advantage of the file manipulation tooling that...

Command-line arguments

So far, we’ve added both variable and fixed (either numeric or string) values to our code. To make our scripts more generic and more usable for other folks, we can add parameters that won’t be hardcoded within the code. If you’re not familiar with the term, hardcoded is the practice of writing fixed variable values within code. In our previous examples, we added the filename that we were going to open as a fixed value – that is, to change it, we would have to change the source code. To avoid that, we could pass the script a value (a filename, in this case) that whoever runs the script can change. Passing values to a script is what we commonly refer to as command-line arguments. We can have multiple arguments, a single argument, or as we’ve done so far, no arguments. Let’s start with a simple example, then work our way up to more complex examples that will help us make our scripts more generic.

Let’s start by...

Putting it all together

Reading and understanding someone else’s code is essential to learning Ruby. With that intent, we will now look at the following example, which was written with some of the techniques we learned about in this chapter, and figure out what the script is doing:

# main.rb
# Section 1: Ruby version validation
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.6')
  puts "Please verify the Ruby version!"
  Kernel::exit(1)
end
# Section 2: Open or create user_name file
file_instance = File.open("user_name.txt", "a+")
user_name = file_instance.read
# Section 3: Empty name validation
if user_name.empty?
  puts "Enter your name:"
  name = gets.chomp
  File.write("user_name.txt", name)
  # Section 4: Program main log
  File.write("main.log", "Writing #{name} as the entry to user_name.txt at #{Time.now}\n"...

Summary

In this chapter, we learned how to write more useful scripts that we will probably reuse in the future. We also got a glimpse at some of the tools that Ruby has to handle text. We also learned how to open, read, and write content to and from a file and how this may come in handy when writing scripts. Lastly, we were exposed to Ruby’s command-line arguments, which make our automation work easier. We also learned of Ruby’s user input arguments, which make our scripts more interactive for users. Having learned this, we are now ready to undercover some misconceptions about PHP, Ruby, Ruby on Rails, and other frameworks.

lock icon The rest of the chapter is locked
You have been reading a chapter from
From PHP to Ruby on Rails
Published in: Dec 2023 Publisher: Packt ISBN-13: 9781804610091
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}