Getting Familiar with Ruby - Developing Your Coding Skills Further - Coding For Dummies (2015)

Coding For Dummies (2015)

Part IV. Developing Your Coding Skills Further

9781118951309-pp0401.tif

webextras.eps See how to program in Ruby and Python at www.dummies.com/extras/coding.

In this part …

· Learn basic programming tasks in Ruby.

· Use Ruby write a simple program to format text.

· Review Python philosophy and basic commands.

· Use Python write a simple program to calculate tips.

Chapter 13. Getting Familiar with Ruby

In This Chapter

arrow Understanding Ruby principles and style

arrow Assigning variables and using if statements

arrow Manipulating strings for consistency and formatting

I hope Ruby helps every programmer be productive, enjoy programming, and be happy. That is the primary purpose of Ruby language.

—Yukihiro Matsumoto, creator of Ruby

Ruby is a server-side language created by Yukihiro “Matz” Matsumoto, a developer who was looking for an easy-to-use scripting language. Matsumoto had experience programming in other languages like Perl and Python, and, unsatisfied with both, created Ruby. When designing Ruby, Matsumoto’s explicit goal was to “make programmers happy”, and he created the language so programmers could easily learn it and use it. It worked. Today Ruby, and particularly Ruby working with a Ruby framework called Rails, is the most popular way for startups and companies to quickly create prototypes and launch websites on the Internet.

In this chapter, you learn Ruby basics, including its design philosophy; how to write Ruby code to perform basic tasks; and steps to create your first Ruby program.

What Does Ruby Do?

Ruby is a general purpose programming language typically used for web development. Until now, the HTML, CSS, and JavaScript you have learned in the previous chapters has not allowed for storing data after the user has navigated away from the page or closed the browser. Ruby makes it easy to store this data, and create, update, store, and retrieve it in a database. For example, imagine I wanted to create a social networking website like Twitter. The content I write in a tweet is stored in a central database. I can exit my browser, and turn off my computer, but if I come back to the website later my tweets are still accessible to me. Additionally, if others search for me or keywords in the tweets I have written, this same central database is queried, and any matches are displayed. Ruby developers frequently perform tasks like storing information in a database, and a Ruby framework called Rails speeds up development by including pre-built code, templates, and easy ways to perform these tasks. For these reasons, websites frequently use Ruby and Rails together.

tip.eps A website using the Rails framework is referred to as being built with Rails or “Ruby on Rails”.

Twitter’s website was one of the most trafficked websites to use Ruby on Rails, and until 2010 used Ruby code for its search and messaging products. Other websites currently using Ruby on Rails include:

· E-commerce websites such as those on the www.shopify.com platform, including The Chivery and Black Milk Clothing.

· Music websites such as www.soundcloud.com.

· Social networking sites such as www.yammer.com.

· News websites such as www.bloomberg.com.

As shown above, Ruby and Rails can create a variety of websites. While Rails emphasizes productivity, allowing developers to quickly write code and test prototypes, some developers criticize Ruby and Rails for not being scalable, and use as evidence Twitter rewriting their code to stop using Rails for many core features. While I cannot resolve the productivity-scalability debate for you here, I can say that Rails can adequately handle millions of visitors per month, and no matter the language used, significant work must be done to scale a website to properly handle tens or hundreds of millions of visitors a month.

tip.eps Confirm the programming language used by these or any major website with BuiltWith available at www.builtwith.com. After entering the website address in the search bar, look under the Frameworks section for Ruby on Rails.

Defining Ruby Structure

Ruby has its own set of design principles that guide how the rest of the language is structured. All the languages you have learned so far have their own conventions, like the curly braces in JavaScript or opening and closing tags in HTML, and Ruby is no different with conventions of its own. The design principles in Ruby explain how Ruby tries to be different from the programming languages that came before it. With these design principles in mind you will then see what Ruby code looks like, understand Ruby’s style, and learn the special keywords and syntax that allow the computer to recognize what you are trying to do. Unlike HTML and CSS, and similar to JavaScript, Ruby can be particular about syntax and misspelling a keyword or forgetting a necessary character will result in the program not running.

Understanding the principles of Ruby

Ruby has a few design principles to make programming in the language less stressful and more fun for programmers of other programming languages. These design principles are:

· Principle of conciseness: In general, short and concise code is needed to create programs. The initial set of steps to run a program written in English is often referred to as pseudo-code. Ruby is designed so as little additional effort is needed to translate pseudo-code into actual code. Even existing Ruby commands can be made more concise. For example, Ruby’s if statement can be written in three lines or just one.

· Principle of consistency: A small set of rules governs the entire language. Sometimes this principle in referred to as the principle of least astonishment or principle of least surprise. In general, if you are familiar with another programming language, the way Ruby behaves should feel intuitive for you. For example, in JavaScript when working with string methods, you can chain them together like so

"alphabet".toUpperCase().concat("Soup")

This JavaScript statement returns “ALPHABETSoup” by first making the string “alphabet” uppercase using the .toUpperCase() method, and then concatenating “soup” to “ALPHABET”. Similarly, the Ruby statement below chains together methods just as you would expect, also returning “ALPHABETSoup”.

"alphabet".upcase.concat("Soup")

· Principle of flexibility: There are multiple ways to accomplish the same thing, and even built-in commands can be changed. For example, when writing an if-else statement you can use the words if and else, but you can also accomplish the task with a single “?”. The following code both perform the same task.

Version 1:

if 3>4
puts "the condition is true"
else
puts "the condition is false"
end

Version 2:

puts 3>4 ? "the condition is false" : "the condition is true"

Styling and spacing

Ruby generally uses less punctuation than other programming languages you may have previously tried. Some sample code is included below.

print "What's your first name?"
first_name = gets.chomp
first_name.upcase!

if first_name=="NIK"
print "You may enter!"
else
print "Nothing to see here."
end

If you ran this code it would do the following:

· Print a line asking for your first name.

· Take user input (gets.chomp) and save it to the first_name variable.

· Test the user input. If it equals “NIK” then print “You may enter!” otherwise print “Nothing to see here.”

Each of these statement types is covered in more detail later in this chapter. For now, as you look at the code, notice some of its styling characteristics

· Less punctuation: unlike JavaScript there are no curly braces, and unlike HTML there are no angle brackets.

· Spaces, tabs, and indentation are ignored: unless within a text string whitespace characters do not matter.

· Newlines indicate the end of statements: although you can use semi-colons to put more than one statement on a line, the preferred and more common method is to put each statement on its own line.

· Dot-notation is frequently used: the period (as in .chomp or .upcase) signals the use of a method, which is common in Ruby. A method is a set of instructions that carry out a particular task. In this code example, .chomp removes carriage returns from the user input, and.upcase transforms the user input into all upper case.

· Exclamation points signal danger: methods applied to variables, like first_name.upcase, by default do not change the variable’s value and only transform a copy of the variable’s value. Exclamation points signal a permanent change, so first_name.upcase! permanently changes the value of the variable first_name.

Coding Common Ruby Tasks and Commands

Ruby can perform many tasks from simple text manipulation to complex login and password user authentication. The following basic tasks, while explained within a Ruby context, are core programming concepts applicable to any programming language. If you have read about another programming language in this book, the following will look familiar. These tasks all take place in the Ruby shell, which looks like a command line interface. Ruby can also generate HTML to create interactive web pages, but that is slightly more complex and not covered here.

Instructions on how to do these basic tasks are below, but you can also practice these skills right away by jumping ahead to the “Building a Simple Form-Text Formatter Using Ruby” section, later in this chapter.

tip.eps Programming languages can do the same set of tasks, and understanding the set of tasks in one language makes it easier to understand the next language.

Defining data types and variables

Variables, like in algebra, are keywords used to store data values for later use. Though the data stored in a variable may change, the variable name will always be the same. Think of a variable like a gym locker — what you store in the locker changes, but the locker number always stays the same.

Variables in Ruby are named using alphanumeric characters and the underscore (_) character, and cannot begin with a number or capital letter. Table 13-1 lists some of the data types that Ruby can store.

Table 13-1 Data Stored by a Variable

Data Type

Description

Example

Numbers

Positive or negative numbers with or without decimals

156–101.96

Strings

Printable characters

Holly NovakSeñor

Boolean

Value can either be true or false

truefalse

To initially set or change a variable’s value, write the variable name and use one equals sign, as shown in the following example:

myName = "Nik"
pizzaCost = 10
totalCost = pizzaCost * 2

tip.eps Unlike JavaScript, Ruby does not require you to use the var keyword to declare a variable, or to set its value the first time.

Variable names are case sensitive, so when referring to a variable in your program remember that MyName is a different variable from myname. In general, give your variable a name that describes the data being stored.

Computing simple and advanced math

After you create variables, you may want to do some math on the numerical values stored in those variables. Simple math like addition, subtraction, multiplication, and division is done using operators you already know. One difference is exponentiation (such as, for example, 2 to the power of 3) is done using two asterisks. Examples are shown below, and in Table 13-2.

sum1 = 1+1 (equals 2)
sum1 = 5-1 (equals 4)
sum1 = 3*4 (equals 12)
sum1 = 9/3 (equals 3)
sum1 = 2**3 (equals 8)

Advanced math like absolute value, rounding to the nearest decimal, rounding up, or rounding down can be performed using number methods, which are shortcuts to make performing certain tasks easier. The general syntax is to follow the variable name or value with a period, and the name of the method as follows for values and variables

value.method
variable.method

technicalstuff.eps The values and variables that methods act upon are called objects. If you compared Ruby to the English language, think of objects like nouns and methods like verbs.

1302

Using strings and special characters

Along with numbers, variables in Ruby can also store strings. To assign a value to a string use single or double quotation marks.

firstname = "Jack"
lastname = 'Dorsey'

To display these variable values, you can puts or print the variable value to the screen. The difference between the two is puts adds a newline (ie., carriage return) after displaying the value, while print does not.

warning.eps Variables can also store numbers as strings instead of numbers. Even though the string looks like a number, Ruby will not be able to perform any operations on it. For example, Ruby cannot evaluate this code as is amountdue = "18" + 24.

One issue arises with strings and variables — what if your string itself includes a single or double quote? For example, if I want to store a string with the value ‘I’m on my way home’ or “Carrie said she was leaving for “just a minute””. As is, the double or single quotes within the string would cause problems with variable assignment. The solution is to use special characters called escape sequences to indicate when you want to use characters like quotation marks, which normally signal the beginning or end of a string, or other non-printable characters like tabs. Table 13-3 shows some examples of escape sequences.

1303

tip.eps Escape sequences are interpreted only for strings with double quotation marks. For a full list of escape sequences, see http://en.wikibooks.org/wiki/Ruby_Programming/Strings.

Deciding with conditionals: If, elsif, else

With data stored in a variable, one common task is to compare the variable’s value to a fixed value or another variable’s value, and then make a decision based on the comparison. If you previously read the JavaScript chapter, you may recall much of the same discussion, and the concept is exactly the same. The general syntax for an if-elsif-else statement is as follows:

if conditional1
statement1 to execute if conditional1 is true
elsif conditional2
statement2 to execute if conditional2 is true
else
statement3 to run if all previous conditionals are false
end

tip.eps Notice there is only one ‘e’ in elsif statement.

The if is followed by a conditional, which evaluates to true or false. If the condition is true, then the statement is executed. This is the minimum necessary syntax needed for an if-statement, and the elseif and else are optional. If present, the elsif tests for an additional condition when the first conditional is false. You can test for as many conditions as you like using elsif. Specifying every condition to test for can become tedious, so it is useful to have a “catch-all”. If present, the else serves this function, and executes when all previous conditionals are false.

tip.eps You cannot have an elsif or an else by itself, without a preceding if statement. You can include many elsif statements, but one and only one else statement.

The conditional in an if statement compares values using comparison operators, and common comparison operators are described in Table 13-4.

1304

Here is an example if statement.

carSpeed=40
if carSpeed > 55
print "You are over the speed limit!"
elsif carSpeed == 55
print "You are at the speed limit!"
else
print "You are under the speed limit!"
end

9781118951309-fg1301.tif

Figure 13-1: An if-else statement with an elsif.

As the diagram in Figure 13-1 shows, there are two conditions, each signaled by the diamond, which are evaluated in sequence. In this example, carSpeed is equal to 40, so the first condition (carSpeed > 55) is false, and then the second conditional (carSpeed==55) is alsofalse. With both conditionals false, the else executes and prints to the screen “You are under the speed limit!”

Input and output

As you have seen in this chapter, Ruby allows you to collect input from and display output to the user. To collect user input use the gets method, which stores the user input as a string. In the following example, the user enters his first name which is stored in a variable calledfull_name:

print "What's your full name?"
full_name = gets

technicalstuff.eps gets might sound like an odd keyword to collect user input. Ruby is influenced by the C programming language, which also has a gets function to collect user input.

Imagine the user entered his name, “Satya Nadella.” As the code is currently written, if you display the value of the variable full_name you would see this

Satya Nadella\n

The \n escape sequence appears after the name because after asking for input the user pressed the “Enter” key, which Ruby stores as \n. To remove the \n add the chomp method to the string, and it will remove the \n and \r escape sequences.

print "What's your full name?"
full_name = gets.chomp

Now when you display the full_name variable you would only see “Satya Nadella”.

To display output to the user you can either use print or puts, short for “put string”. The difference between the two is that puts adds a newline after executing, while print does not. The following code shows the difference when print and puts is executed.

Print code:

print "The mission has "
print "great tacos"

Result:

The mission has great tacos

Puts code:

puts "The mission has "
puts "great tacos"

Result:

The mission has
great tacos

Shaping Your Strings

Manipulating strings is one of the most common tasks for a programmer. Sample tasks in this category include:

· Standardizing strings to have consistent upper- and lowercase.

· Removing white space from user input.

· Inserting variables values in strings displayed to the user.

Ruby shines when it comes to dealing with strings, and includes many built-in methods that make processing strings easier in Ruby than in other languages.

String methods: upcase, downcase, strip

Standardizing user input to have proper case and remove extra white space characters is often necessary to easily search the data later. For example, imagine you are designing a website for the New York Department of Motor Vehicles, and one page is for driver license application and renewals. Both the application and renewal forms ask for current address, which includes a field for two letter state abbreviation. After reviewing completed paper forms, and previous electronic data you see that drivers enter the state in several ways including “NY”, “ny”, “Ny”, “ ny “, “nY”, and other similar variants. If “NY” was the desired result you could use upcase and strip to make this input consistent. Table 13-5 further describes these string methods.

1305

Inserting variables in strings with #

To insert variable values into strings shown to the user, you can use the hashtag sequence #{...}. The code between the open and closing curly braces is evaluated and inserted into the string. Like with escape sequences, the variable value is inserted only into strings created with double quotation marks. See the example code and result below.

Code:

yearofbirth = 1990
pplinroom = 20
puts "Your year of birth is #{yearofbirth}. Is this correct?"
puts 'Your year of birth is #{yearofbirth}. Is this correct?'
puts "There are #{pplinroom / 2} women in the room with the same birth year."

Result:

Your year of birth is 1990. Is this correct?
Your year of birth is #{yearofbirth}. Is this correct?
There are 10 women in the room with the same birth year.

The first string used double quotes and the variable was inserted into the string and displayed to the user. The second string used single quotes so the code inside the curly braces was not evaluated, the variable value was not inserted, and instead #{yearofbirth} was displayed. The third string shows that any code can be evaluated and inserted into the string.

technicalstuff.eps This method of inserting variable values into strings is called string interpolation.

Building a Simple Form-Text Formatter Using Ruby

Practice your Ruby online using the Codecademy website. Codecademy is a free website created in 2011 to allow anyone to learn how to code right in the browser, without installing or downloading any software. Practice all of the tags (and a few more) that you learned in this chapter by following these steps:

1. Open your browser, go to www.dummies.com/go/codingfd, and click on the link to Codecademy.

2. Sign in to your Codecademy account.

Signing up is discussed in Chapter 3. Creating an account allows you to save your progress as you work, but it’s optional.

3. Navigate to and click on Introduction to Ruby to practice some basic Ruby commands.

4. Background information is presented in the upper left portion of the site, and instructions are presented in the lower left portion of the site.

5. Complete the instructions in the main coding window.

6. After you have finished completing the instructions, click the Save and Submit Code button.

If you have followed the instructions correctly, a green checkmark appears, and you proceed to the next exercise. If an error exists in your code a warning appears with a suggested fix. If you run into a problem, or have a bug you cannot fix, click on the hint, use the Q&A Forums, or tweet me at @nikhilgabraham and include hashtag #codingFD.