Chapter 13
IN THIS CHAPTER
Understanding Ruby principles and style
Assigning variables and using if
statements
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.
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.
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:
www.shopify.com
platform, including The Chivery and Black Milk Clothing.www.soundcloud.com
.www.yammer.com
.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.
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.
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:
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"
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:
gets.chomp
) and save it to the first_name
variable.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
.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.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
.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.
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
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.
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)
TABLE 13-2 Common Ruby Number Methods
Method Name |
Description |
Example |
Result |
|
Returns the absolute value of a number |
- |
|
|
Rounds a number to n digits |
|
|
|
Rounds down to the nearest integer |
|
|
|
Rounds up to the nearest integer |
|
|
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
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.
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.
TABLE 13-3 Common Ruby Escape Sequences
Special Character |
Description |
Example |
Result |
|
Quotation marks |
|
|
|
Tab |
|
|
|
Newline |
|
|
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
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
.
The conditional in an if
statement compares values using comparison operators, and common comparison operators are described in Table 13-4.
TABLE 13-4 Common Ruby Comparison Operators
Type |
Operator |
Description |
Example |
Less than |
|
Evaluates whether one value is less than another value |
|
Greater than |
|
Evaluates whether one value is greater than another value |
|
Equality |
|
Evaluates whether two values are equal |
|
Less than or equal to |
|
Evaluates whether one value is less than or equal to another value |
|
Greater than or equal to |
|
Evaluates whether one value is greater than or equal to another value |
|
Inequality |
|
Evaluates whether two values are not equal |
|
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
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 also false
. With both conditionals false, the else
executes and prints to the screen “You are under the speed limit!”
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 called full_name
:
print "What's your full name?"
full_name = gets
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
The
escape sequence appears after the name because after asking for input the user pressed the “Enter” key, which Ruby stores as
. To remove the
add the chomp
method to the string, and it will remove the
and
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
Manipulating strings is one of the most common tasks for a programmer. Sample tasks in this category include:
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.
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.
TABLE 13-5 Select Ruby String Methods
Method Name |
Description |
Example |
Result |
|
Returns all uppercase characters |
|
|
|
Returns all lowercase characters |
|
|
|
Capitalizes first letter, lowercases remaining letters |
|
|
|
Removes leading and trailing whitespaces |
|
|
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.
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:
www.dummies.com/go/codingfd
, and click on the link to Codecademy.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.
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
.
3.145.188.160