Writing A Ruby Program: Part I

Photo by Joshua Fuller on Unsplash

I remember back in my early BootCamp days, and I was learning how to work with Ruby. It felt as though every assignment involved the phrase “Hello World!” and I wanted to scream; however, somehow, when that string returned, I also shouted with glee because I solved the assignment correctly. Fast forward, I’ve since learned Ruby on Rails, JavaScript, and React, but I haven’t gone back to those old school days of just Ruby and Ruby alone.

In this tutorial, I’m going to walk you through creating a program in Ruby. But to make it more interesting, we’ll have the program ask for the user’s name. In the end, it should look like this:

Getting Started

So let’s get started writing a new program and create a new file by doing the following: touch greetings.rb or the “New File” option in the VS Code Editor.

Once greeting.rb is created, we’ll begin a typing out our greeting:

So in this code snippet, we’re using puts and \n . puts is a Ruby method used to tell the computer to print text to the screen. In addition to puts , I also used \n to create a new line.

gets.chop

So now that we have the introduction set up, we can prompt the user for their name so we can use it in a response. We’ll start by using the puts method to request the user’s name.

Next, we’ll create a variable to store the input given by the user by using another method called gets. But instead of using name = gets , we’ll be using name = gets.chomp instead. The reasoning behind this is due to the creation of a new-line character when you use gets . You can check out my previous blog about using gets methods here.

So if we continue, your code should look like the following:

Running a Ruby program

So now that you have your code, it’s time to run your program. We’ll start by using the ruby command and follow it up with the name of the Ruby file. It should be like follows:

Once it runs, you’ll see the greeting and prompt asking you the following question:

Now that you’ve learned how to create a file, get input, and run a program, you can continue adding to your program. Feel free and comment and share. Thanks for reading!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joy Evans

Software Engineer | C# | Angular | Ruby on Rails | Javascript | React