Learn Enough Ruby To Be Dangerous Write Programs Publish Gems And Develop Sinatra Web Apps With Ruby Michael Hartl pdf download
Learn Enough Ruby To Be Dangerous Write Programs Publish Gems And Develop Sinatra Web Apps With Ruby Michael Hartl pdf download
https://ebookbell.com/product/learn-enough-ruby-to-be-dangerous-
write-programs-publish-gems-and-develop-sinatra-web-apps-with-
ruby-michael-hartl-46132216
https://ebookbell.com/product/learn-enough-ruby-to-be-dangerous-write-
programs-publish-gems-and-develop-sinatra-web-apps-with-ruby-michael-
hartl-46145114
https://ebookbell.com/product/learn-enough-html-css-and-layout-to-be-
dangerous-lee-donahoe-43239934
https://ebookbell.com/product/learn-enough-javascript-to-be-dangerous-
michael-hartl-43239956
https://ebookbell.com/product/learn-enough-developer-tools-to-be-
dangerous-michael-hartl-43239958
Learn Enough Developer Tools To Be Dangerous 1st Edition Michael Hartl
https://ebookbell.com/product/learn-enough-developer-tools-to-be-
dangerous-1st-edition-michael-hartl-60673238
https://ebookbell.com/product/learn-enough-javascript-to-be-dangerous-
a-tutorial-introduction-to-programming-with-javascript-michael-
hartl-45491534
https://ebookbell.com/product/learn-enough-developer-tools-to-be-
dangerous-git-version-control-command-line-and-text-editors-
essentials-rough-cuts-michael-hartl-38659586
https://ebookbell.com/product/learn-enough-html-css-and-layout-to-be-
dangerous-an-introduction-to-modern-website-creation-and-templating-
systems-lee-donahoe-43771502
https://ebookbell.com/product/learn-enough-command-line-to-be-
dangerous-michael-hartl-11712992
About This eBook
ePUB is an open, industry-standard format for eBooks. However,
support of ePUB and its many features varies across reading devices and
applications. Use your device or app settings to customize the presentation
to your liking. Settings that you can customize often include font, font size,
single or double column, landscape or portrait mode, and figures that you
can click or tap to enlarge. For additional information about the settings and
features on your reading device or app, visit the device manufacturer’s Web
site.
Many titles include programming code or configuration examples. To
optimize the presentation of these elements, view the eBook in single-
column, landscape mode and adjust the font size to the smallest setting. In
addition to presenting code and configurations in the reflowable text
format, we have included images of the code that mimic the presentation
found in the print book; therefore, where the reflowable format may
compromise the presentation of the code listing, you will see a “Click here
to view code image” link. Click the link to view the print-fidelity code
image. To return to the previous page viewed, click the Back button on
your device or app.
Praise for Learn Enough Tutorials
“Ruby and Sinatra and Heroku, oh my! Almost done with this live web
application. It may be a simple palindrome app, but it’s also simply
exciting! #100DaysOfCode #ruby @LearnEnough #ABC
#AlwaysBeCoding #sinatra #heroku”
—Tonia Del Priore (@toninjaa), Twitter post
Software Engineer for a FinTech Startup for 3+ years
“I want to thank you for the amazing job you have done with the tutorials.
They are likely the best tutorials I have ever read.”
—Pedro Iatzky
Learn Enough Ruby to Be
Dangerous
Michael Hartl
The author and publisher have taken care in the preparation of this book,
but make no expressed or implied warranty of any kind and assume no
responsibility for errors or omissions. No liability is assumed for incidental
or consequential damages in connection with or arising out of the use of the
information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales
opportunities (which may include electronic versions; custom cover
designs; and content particular to your business, training goals, marketing
focus, or branding interests), please contact our corporate sales department
at [email protected] or (800) 382-3419.
1 Hello, World!
1.1 Introduction to Ruby
1.2 Ruby in a REPL
1.2.1 Exercises
1.3 Ruby in a File
1.3.1 Exercises
1.4 Ruby in a Shell Script
1.4.1 Exercises
1.5 Ruby in a Web Browser
1.5.1 Deployment
1.5.2 Exercises
2 Strings
2.1 String Basics
2.1.1 Exercises
2.2 Concatenation and Interpolation
2.2.1 Single-Quoted Strings
2.2.2 Exercises
2.3 Printing
2.3.1 Exercises
2.4 Attributes, Booleans, and Control Flow
2.4.1 Combining and Inverting Booleans
2.4.2 Bang Bang
2.4.3 Exercises
2.5 Methods
2.5.1 Exercises
2.6 String Iteration
2.6.1 Exercises
3 Arrays
3.1 Splitting
3.1.1 Exercises
3.2 Array Access
3.2.1 Exercises
3.3 Array Slicing
3.3.1 Exercises
3.4 More Array Methods
3.4.1 Sorting and Reversing
3.4.2 Pushing and Popping
3.4.3 Undoing a Split
3.4.4 Exercises
3.5 Array Iteration
3.5.1 Exercises
6 Functional Programming
6.1 Map
6.1.1 Exercises
6.2 Select
6.2.1 Exercises
6.3 Reduce
6.3.1 Reduce, Example 1
6.3.2 Reduce, Example 2
6.3.3 Functional Programming and TDD
6.3.4 Terminology Review
6.3.5 Exercises
9 Shell Scripts
9.1 Reading from Files
9.1.1 Exercises
9.2 Reading from URLs
9.2.1 Exercises
9.3 DOM Manipulation at the Command Line
9.3.1 Exercises
10 A Live Web Application
10.1 Setup
10.1.1 Exercises
10.2 Site Pages
10.2.1 Exercises
10.3 Layouts
10.3.1 Exercises
10.4 Embedded Ruby
10.4.1 Exercises
10.5 Palindrome Detector
10.5.1 Form Tests
10.5.2 Exercises
10.6 Conclusion
Preface
Learn Enough Ruby to Be Dangerous teaches you to write practical and
modern programs using the elegant and powerful Ruby programming
language. You’ll learn how to use Ruby for both general-purpose
programming and for beginning web-application development. Although
mastering Ruby can be a long journey, you don’t have to learn everything to
get started… you just have to learn enough to be dangerous.
You’ll begin by exploring the core concepts of Ruby programming using
a combination of interactive Ruby and text files run at the command line.
The result is a solid understanding of both object-oriented programming
and functional programming in Ruby. You’ll then build on this foundation
to develop and publish a simple self-contained Ruby package, or Ruby
gem. You’ll then use this gem in a simple dynamic web application built
using the Sinatra web framework, which you’ll also deploy to the live Web.
As a result, Learn Enough Ruby to Be Dangerous is especially appropriate
as a prerequisite to the Ruby on Rails Tutorial, a bestselling web-
development tutorial by the same author.
In addition to teaching you specific skills, Learn Enough Ruby to Be
Dangerous also helps you develop technical sophistication—the seemingly
magical ability to solve practically any technical problem. Technical
sophistication includes concrete skills like version control and coding, as
well as fuzzier skills like Googling the error message and knowing when to
just reboot the darn thing. Throughout Learn Enough Ruby to Be
Dangerous, we’ll have abundant opportunities to develop technical
sophistication in the context of real-world examples.
Chapter by Chapter
In order to learn enough Ruby to be dangerous, we’ll begin at the beginning
with a series of simple “hello, world” programs using several different
techniques (Chapter 1), including an introduction to irb, an interactive
command-line program for evaluating Ruby code. In line with the Learn
Enough philosophy of always doing things “for real”, even as early as
Chapter 1 we’ll deploy a (very simple) dynamic Ruby application to the
live Web.
After mastering “hello, world”, we’ll take a tour of some Ruby objects,
including strings (Chapter 2), arrays (Chapter 3), and other native objects
like dates, hashes, and regular expressions (Chapter 4). Taken together,
these chapters constitute a gentle introduction to object-oriented
programming with Ruby.
In Chapter 5, we’ll learn the basics of functions, an essential subject for
virtually every programming language. We’ll then apply this knowledge to
an elegant and powerful style of coding known as functional programming
(Chapter 6).
Having covered the basics of built-in Ruby objects, in Chapter 7 we’ll
learn how to make objects of our own. In particular, we’ll define an object
for a phrase, and then develop a method for determining whether or not the
phrase is a palindrome (the same read forward and backward).
Our initial palindrome implementation will be rather rudimentary, but
we’ll extend it in Chapter 8 using a powerful technique called test-driven
development (TDD). In the process, we’ll learn more about testing
generally, as well as how to create a Ruby gem.
In Chapter 9, we’ll learn how to write nontrivial shell scripts, one of
Ruby’s biggest strengths. Examples include reading from both files and
URLs, with a final example showing how to manipulate a downloaded file
as if it were an HTML web page.
In Chapter 10, we’ll develop our first full Ruby web application: a site
for detecting palindromes. This will give us a chance to learn about routes,
layouts, embedded Ruby, and form handling, together with a second
application of TDD. As a capstone to our work, we’ll deploy our
palindrome detector to the live Web.
Additional Features
In addition to the main tutorial material, Learn Enough Ruby to Be
Dangerous includes a large number of exercises to help you test your
understanding and to extend the material in the main text. The exercises
include frequent hints and often include the expected answers, with
community solutions available by separate subscription at
www.learnenough.com.
Final Thoughts
Learn Enough Ruby to Be Dangerous gives you a practical introduction to
the fundamentals of Ruby, both as a general-purpose programming
language and as a web-development specialist. After learning the
techniques covered in this tutorial, and especially after developing your
technical sophistication, you’ll know everything you need to write shell
scripts, publish Ruby gems, and deploy dynamic web applications with
Ruby. You’ll also be ready for a huge variety of other resources, including
books, blog posts, and online documentation. A particularly good next step
is learning how to make dynamic database-backed web applications with
the Ruby on Rails Tutorial.
Finally, experienced developers can largely skip the first four chapters,
as described in Box 1.2.
This standardizes on Ruby 3, but any version of Ruby later than 2.7 should
be fine for this tutorial. If instead you get a result like
or you get a version number earlier than 2.7, then you will have to install a
more recent version of Ruby.
The details of installing Ruby vary by system and can require applying a
little technical sophistication (Box 1.1). The different possibilities are
covered in Learn Enough Dev Environment to Be Dangerous, which you
should take a look at now if you don’t already have Ruby on your system.
In particular, if you end up using the cloud IDE recommended by Learn
Enough Dev Environment to Be Dangerous, you can update the Ruby
version as follows:
$ irb
>>
Here >> represents a generic irb prompt, which you can achieve on your
system by editing a special configuration file called .irbrc. Start by
creating .irbrc in your home directory using the text editor of your choice:3
3I generally use Sublime Text or Atom for everyday editing, but for editing short configuration
files and the like I usually use Vim. The reason is that Vim is incredibly fast to open and quit, which
is especially convenient when the editing task itself takes only a few seconds.
$ vim ~/.irbrc
Then fill the file with the contents of Listing 1.3. This arranges to simplify
the irb prompt as in Listing 1.2 while suppressing some annoying auto-
indent behavior.
To apply this configuration, you should exit irb using exit or Ctrl-D and
then rerun the irb command.
With that bit of configuration done, we’re now ready to write our first
Ruby program using the puts command (pronounced “put-ess”), which
stands for “put string”, as seen in Listing 1.4. (We’ll start learning about
strings in Chapter 2.)
That’s it! That’s how easy it is to print “hello, world!” interactively with
Ruby.
If you’re familiar with other programming languages (such as
JavaScript), Listing 1.4 is notable for its lack of both parentheses and a
terminating semicolon. Cleaning up punctuation in this way is very
“Rubyish”, i.e., characteristic of Ruby.
You might also note that the final line in Listing 1.4 includes a return
value, which for puts is nil, a special Ruby value that means “nothing at
all”. We’ll learn more about nil starting in Section 2.3.
1.2.1 Exercises
1. What happens if you use print in place of puts? How would you
change print’s argument to get the result to match Listing 1.4? Hint:
Recall that \n is the typical way to represent a newline character.
At this point, we’re ready to execute our program using the ruby
command we used in Listing 1.1 to check the Ruby version number. The
only difference is that this time we omit the -v flag and instead include an
argument with the name of our file:
$ ruby hello.rb
hello, world!
As in Listing 1.4, the result is to print “hello, world!” to the terminal screen,
only now it’s the raw shell instead of an irb REPL.
Although this example is simple, it’s a huge step forward, as we’re now
in the position to write Ruby programs much longer than could comfortably
fit in an irb session.
1.3.1 Exercises
1. What happens if you give puts two arguments, as in Listing 1.6?
Listing 1.6: Using two arguments.
hello.rb
$ touch hello
Note that we didn’t include the .rb extension—this is because the filename
itself is the user interface, and there’s no reason to expose the
implementation language to the user. Indeed, there’s a reason not to: By
using the name hello, we give ourselves the option to rewrite our script in a
different language down the line, without changing the command our
program’s users have to type. (Not that it matters in this simple case, but the
principle should be clear. We’ll see a more realistic example in Section 9.3.)
There are two steps to writing a working script. The first is to use the
same command we’ve seen before (Listing 1.5), preceded by a “shebang”
line telling our system to use ruby to execute the script.
Ordinarily, the exact shebang line is system-dependent (as seen with
Bash in Learn Enough Text Editor to Be Dangerous and with JavaScript in
Learn Enough JavaScript to Be Dangerous), but with Ruby we can ask the
shell itself to supply the proper command. The trick is to use the ruby
executable available as part of the shell’s environment (env):
#!/usr/bin/env ruby
Using this for the shebang line gives the shell script shown in Listing 1.7.
$ chmod +x hello
$ ./hello
hello, world!
Success! We’ve now written a working Ruby shell script suitable for
extension and elaboration. As mentioned briefly above, we’ll see an
example of a real-life utility script in Section 9.3.
Throughout the rest of this tutorial, we’ll mainly use irb for initial
investigations, but the eventual goal will almost always be to create a file
(either pure code or HTML) containing Ruby.
1.4.1 Exercises
1. By moving the file or changing your system’s configuration, add the
hello script to your environment’s PATH. (You may find the steps in
Learn Enough Text Editor to Be Dangerous helpful.) Confirm that
you can run hello without prepending ./ to the command name.
Note: If you have a conflicting hello program from following Learn
Enough JavaScript to Be Dangerous, I suggest replacing it—thus
demonstrating the principle that the file’s name is the user interface,
and the implementation can change language without affecting users.
Now we’re ready to install sinatra using the gem command, which is
installed automatically as part of Ruby:
Believe it or not, this one command installs all of the software needed to
run a simple but full-strength web application on our local system (where
“local” might refer to the cloud if you’re using the cloud IDE recommended
in Learn Enough Dev Environment to Be Dangerous).
Although the code for the “hello, world” web app uses commands that
we haven’t covered yet, it’s a straightforward adaptation of the example
program on the Sinatra homepage (Figure 1.4). Being able to adapt code
you don’t necessarily understand is a classic hallmark of technical
sophistication (Box 1.1).
Figure 1.4: A sample program from the Sinatra homepage.
$ touch hello_app.rb
The code itself closely parallels the program in Figure 1.4, as seen in
Listing 1.8. (If you’re wondering about the use of both single-quoted strings
in Listing 1.8 and the double-quoted strings we saw in Section 1.2, you’re
ahead of the game; we’ll learn the difference between the two in Chapter 2.)
get '/' do
'hello, world!'
end
We’ll cover the techniques in Listing 1.8 in more detail starting in Section
5.4, but the basic idea is that it defines the behavior for the root URL / when
responding to an ordinary browser request (known as GET). The response
itself is the required “hello, world!” string, which will be returned to the
browser as a (very simple) web page.
To run the web application in Listing 1.8, all we need to do is call the
hello_app.rb file using the same ruby command we used in Section 1.3;
the sinatra gem magically takes care of the rest (Listing 1.9).
Here I’ve shown the output on my system, which runs a local web server on
port number 4567 by default. This means you can view the app by visiting
localhost:4567 in your browser. As seen in Figure 1.5, the effect on the
cloud IDE is slightly different, but the idea is basically the same, and in
either case the result should look something like Figure 1.6.
Figure 1.5: The “local” server running on the cloud IDE.
Figure 1.6: The hello app running locally.
It’s worth noting that using Ruby to run a Sinatra app as in Listing 1.9
suffers from a major inconvenience: Seeing the effect of changes to the
code requires quitting and restarting the server. This is fine for a quick
change, but quickly becomes impractical for larger projects. We’ll see how
to get around this restriction using the rerun gem starting in Section 10.1.
1.5.1 Deployment
Now that we’ve got our app running locally, we’re ready to deploy it to a
production environment. This used to be practically impossible to do in a
beginning tutorial, but nowadays we can do it using a great hosting platform
called Heroku. There’s a bit of overhead to deploy something the first time,
but deploying early and often is a core part of the Learn Enough philosophy
of shipping (Box 1.3). Moreover, a simple app like “hello, world” is the
best kind of app for first-time deployment, because there’s so much less that
can go wrong.
Although not strictly necessary, it’s a good idea to push any newly
initialized repository up to a remote backup. As in previous Learn Enough
tutorials, we’ll use GitHub for this purpose (Figure 1.7).5
5Previous versions of this tutorial used GitLab instead of GitHub because at the time private
repos at GitHub weren’t free. Since videos are harder to update than text, the screencasts that
accompany this book still use GitLab, but the steps for GitHub are much the same (and are covered
in several other Learn Enough tutorials, including Learn Enough Git to Be Dangerous). As usual, use
your technical sophistication (Box 1.1) to resolve any discrepancies.
Figure 1.7: Creating a new repository at GitHub.
Next, configure your local system with the remote repository and push it
up (taking care to fill in <username> with your GitHub username and using
a GitHub personal access token when prompted for a password):
This will display the current version number if the heroku command-line
interface (CLI) is available, but on most systems it will be necessary to
install the Heroku CLI by hand.6 In particular, if you’re working on the
cloud IDE, you can install Heroku using the command shown in Listing
1.10.
6toolbelt.heroku.com
After running the command in Listing 1.10, you should now be able to
verify the installation by displaying the current version number (details may
vary):
If you’re using the cloud IDE, you need to pass the --interactive
option, which prevents the heroku command from trying to spawn a
browser (which wouldn’t work in the cloud). You also won’t be able to log
in using your regular Heroku password; instead, you’ll have to create an
API Key using the interface on your Heroku Account page (Figure 1.9).
Once you’ve followed that step (and saved the result somewhere safe), you
can log in using your email and the Account Key as your password:
Figure 1.9: The API key at Heroku.
After you’ve logged in, you can use the heroku create command to
create a place on the Heroku servers for the sample app to live (Listing
1.11).
Finally, use the heroku create command to create a place on the Heroku
servers for the sample app to live (Listing 1.11).
The heroku command creates a new subdomain just for our application,
available for immediate viewing. There’s nothing there yet, though, so let’s
get busy deploying.
The final steps involve some configuration that you can practically copy
(with only minor modifications) from the Heroku documentation. We need
only two more files, a “Rackup” (.ru) file called config.ru and a Gemfile
specifying which gems our app uses (in this case, sinatra and puma, which
is a production-grade web server):
Using your favorite text editor, fill these files with the contents shown in
Listing 1.12 and Listing 1.13.
Now we’re almost ready to deploy. We first need to bundle our gems
(well, gem) using Bundler, and then add the files to Git:
Note that the first three lines include an exact Bundler version number
(2.3.10) for maximum compatibility. The third line may or may not be
necessary depending on the exact system you’re using, but in any case it
does no harm to include it.
Finally, we can deploy to Heroku with a simple git push:
That’s it! Once the deployment is complete, our hello app is running in
production (Figure 1.10). (Note: Heroku displays the Web URL of the app
upon deployment, but you can run heroku apps:info at any time to see it
again.)
Figure 1.10: The hello app running in production.
SUCCESSORS TO
ebookbell.com