Chapter 6

Programming with Ruby and Python

In This Chapter

arrow Discovering what Ruby and Python do

arrow Checking out Ruby and Python code

arrow Choosing a programming language to learn first

The sooner you start to code, the longer the program will take.

Roy Carlson

Ruby and Python are server-side programming languages that allow developers to create complex applications and web experiences. HTML, CSS, and JavaScript have been used to display static information to users, but could not store user data after the user navigates away from the page or closes the browser. Using Ruby or Python, user information can be stored centrally, and then programmers can customize the information shown to users on the website.

In this chapter you learn the basics of using languages such as Ruby and Python, you write some simple code, and you discover resources to learn more advanced Ruby and Python topics.

Introducing Ruby and Python

Ruby is a general-purpose programming language typically used for web development. The programming language makes it easy to create, update, store, and retrieve data in a database. For example, suppose you want to create a social networking website like Twitter. The content you write in your tweet will be stored in a central database. You can exit the browser and turn off your computer, but when you come back to the website later, you can still access your tweets. Additionally, if someone searches for keywords in the tweets you’ve written, this same central database will be queried, and any matches will be displayed.

Ruby developers frequently perform tasks such as storing information in a database, and a Ruby framework called Rails speeds development by including prebuilt code, templates, and easy ways to perform these tasks. For these reasons, websites frequently use Ruby and Rails together.

tip A website using the Rails framework is referred to as being “built with Rails” or “built using 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. Following are other types of websites currently using Ruby on Rails:

As you can see, Ruby and Rails can create a variety of websites. Although Rails emphasizes productivity, allowing developers to quickly write code and test prototypes, some developers criticize Ruby and Rails for not being scalable and cite as evidence Twitter rewriting their code to stop using Rails for many core features in an effort to improve the website’s speed and increase the website’s capability to handle more users at the same time.

I can’t resolve the scalability debate here, but 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 monthly visitors.

tip You can confirm the programming language used by any major website with BuiltWith, which is available at www.builtwith.com. After entering the website address in the search bar, look under the Frameworks section for the programming language used. An example is shown in Figure 6-1.

image

Figure 6-1: Shopify, the e-commerce platform, uses Ruby on Rails for its website.

Like Ruby, Python is a general-purpose programming language used for web development. Both languages are more alike than they are different. Python, like Ruby but unlike HTML, CSS, and JavaScript, allows for storing data after the user has navigated away from the page or closed the browser. Python includes prebuilt code to easily create and query these databases.

technicalstuff SQLite is a free lightweight database commonly used by Python programmers to store data.

Many highly trafficked websites, such as YouTube, were created using Python. Other websites currently using Python include

  • Quora, for its community question and answer site
  • Spotify, for internal data analysis
  • Dropbox, for its desktop client software
  • Reddit, for generating crowd-sourced news
  • Industrial Light & Magic and Disney Animation, for creating film special effects.

From websites to software to special effects, Python is a versatile language, powerful enough to support a range of applications.

Python programmers help spread Python code by creating libraries, which are standalone prewritten code that performs certain tasks. For example, a library called Scrapy performs web scraping (data extraction from websites), and another library called SciPy performs math functions used by scientists and mathematicians. The Python community maintains thousands of libraries like these; most are free to use as well as open-source, so anyone may modify them.

In addition, just like the Rails framework makes developing Ruby applications for the web easier, Django and Flask are two frameworks that make it easier to code web applications in Python.

Coding Advanced Functionality

Ruby and Python each have design principles that guide how the language is structured. In addition, each has conventions that guide how the language is written, like the curly braces in JavaScript or opening and closing tags in HTML.

In this section, I describe the design principles and show you what the code looks like. After this basic overview, you can learn more by checking out the referenced resources, along with Part III of this book.

Ruby design principles and code

Ruby was created by Yukhiro “Matz” Matsumoto, a developer with experience programming in Perl and Python, Unsatisfied with both and wanting an easy-to-use scripting language, he created Ruby.

When designing Ruby, Matsumoto’s explicit goal was to “make programmers happy.” He created the language so that programmers could learn and use it easily. Today, Ruby is a popular way for startups and companies to quickly create prototypes and launch websites on the Internet.

A few design principles make programming in Ruby less stressful and more fun than other programming languages. These design principles follow:

  • Conciseness: In general, short and concise code helps create faster and easier-to-read programs. The initial set of steps written in English to run a program is referred to as pseudocode. Ruby is designed so that little additional effort is needed to translate pseudocode 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.
  • Consistency: A small set of rules governs the entire language. Sometimes this principle in referred to as the principle of least astonishment or the principle of least surprise. In general, if you’re familiar with another programming language, the way Ruby behaves should feel intuitive. For example, when working with string methods in JavaScript, you can chain them together as follows:

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

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

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

  • 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, or you can use a single ?. The following versions of 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 follows:

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:

  1. Print a line asking for your first name.
  2. Take user input (gets.chomp) and save it to the first_name variable.
  3. Transform any inputted text into uppercase.
  4. Test the user input. If the input equals “NIK” then the code would print “You may enter!”; otherwise, it prints “Nothing to see here.”

Don’t worry if these statements and commands seem foreign to you. For now, as you look at the code, notice some of its styling characteristics:

  • Less punctuation: Ruby, unlike JavaScript, does not have curly braces, and unlike HTML, does not have angle brackets.
  • Space, tab, and indentation are ignored: These whitespace characters do not matter unless they are in a text string.
  • A newline indicates the end of a statement: Although you can use a semicolon 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 (for example, .chomp or .upcase) signals the use of a method, which is a set of instructions that carry out a particular task. In this code example, .chomp removes carriage returns from user input, and .upcase transforms the user input into uppercase.
  • An exclamation point signals danger: A method applied to a variable, such as first_name.upcase, by default transforms a copy of the variable’s value, not the value itself. An exclamation point signals a permanent change, so first_name.upcase! permanently changes the value of the variable first_name.

tip To learn more Ruby, see Chapters 9 and 10 for additional resources. You might also want to check out www.codecademy.com and www.tryruby.org for some free, short, self-taught lessons.

Python design principles and code

Python was created by Guido van Rossum, a developer who was bored during the winter of 1989 and looking for a project to do. Van Rossum had helped create one language, ABC, and the experience had given him many ideas that he thought would appeal to programmers. He executed these ideas when he created Python.

Although ABC never achieved popularity with programmers, Python was a runaway success. Python is one of the world’s most popular programming languages, used by those just starting out as well as professionals building heavy-duty applications.

The Zen of Python, a poem that is part of the Python documentation, contains nineteen design principles that describe how the Python language is organized. Some of the most important principles include the following:

  • Readability counts: This is possibly Python’s most important design principle. Python code looks similar to English and even enforces certain formatting, such as indenting, to make the code easier to read. With highly readable code, you’ll find it much easier to fix a bug or add a feature months later. Readable code also means others can use your code or help debug your code with ease.

    technicalstuff Reddit.com is one of the top 10 most visited websites in the US, and one of the top 50 most visited websites in the world. Its cofounder, Steve Huffman, initially coded the website in Lisp but switched to Python because it is “extremely readable, and extremely writeable.”

  • There should be one — and preferably only one — obvious way to do it: This principle is directly opposite Perl’s motto, “There’s more than one way to do it.” In Python, two programmers may approach the same problem and write two different programs, but the ideal is that the code will be similar and easy to read, adopt, and understand. Although Python may allow you to perform a task (such as combining two strings) in multiple ways, you should use the most obvious and common option.
  • If the implementation is hard to explain, it’s a bad idea: Programmers have been known to write esoteric code to increase performance. However, Python was designed to be easy to use, and this principle reminds programmers that easy-to-understand implementations are preferable over faster but harder-to-explain ones.

tip Access the full list of design principles, which is in the form of a poem, by typing import this; in any Python interpreter, or by visiting www.python.org/dev/peps/pep-0020. These principles, written by Python community member Tim Peters, describe the intentions of Python’s creator, Van Rossum, who is also referred to as the Benevolent Dictator for Life (BDFL).

Python generally uses less punctuation than other programming languages you may have previously tried. Some sample code is included here:

first_name=raw_input(“What’s your first name?”)

first_name=first_name.upper()

if first_name==“NIK”:

   print “You may enter!”

else:

   print “Nothing to see here.”

technicalstuff The examples in this book are written for Python 2.7. Two popular versions of Python are currently in use: Python 2.7 and Python 3. Python 3 is the latest version of the language but it is not backwards compatible, so code written using Python 2.7 syntax does not work when using a Python 3 interpreter. Initially, Python 2.7 had more external libraries and support than Python 3, but this is changing. For more about the differences between the two versions, see https://wiki.python.org/moin/Python2orPython3.

If you ran this code, it would do the following:

  1. Print a line asking for your first name.
  2. Take the user input (raw_input(What’s your first name?)) and save it to the first_name variable.
  3. Transform any inputted text into uppercase.
  4. Test the user input. If the input equals “NIK,” the code will print “You may enter!” Otherwise it prints “Nothing to see here.”

These commands are similar to Ruby. For now, as you look at the code, note some of its styling characteristics:

  • Less punctuation: Python, unlike JavaScript, does not have curly braces, and unlike HTML, does not have angle brackets.
  • Whitespace matters: Statements indented to the same level are grouped together. In the preceding example, note how the if and else align, and the print statements below each are indented the same amount. You can decide the amount of indentation, and whether to use tabs or spaces, as long as you are consistent. Four spaces from the left margin is considered the norm.

    tip See Python style suggestions on indentation, whitespace, and commenting by visiting www.python.org/dev/peps/pep-0008.

  • A newline indicates the end of a statement: Although you can use semicolons to put more than one statement on a line, the preferred and more common method is to put each statement on its own line.
  • A colon separates a code block: Some new Python programmers wonder why they should use colons to indicate code blocks, like the one at the end of the if statement, when using newlines would suffice. Early user testing with and without the colons showed that beginner programmers better understood the code with the colon.

tip To learn more about Python, see Chapters 9 and 10. If you can’t wait, check out www.codecademy.com or developers.google.com/edu/python for some free, short, self-taught lessons.

Choosing between Ruby and Python

When you’re just starting out, decide which language to learn first can be difficult. Ruby and Python are two popular programming languages for web development, so you can’t go wrong with learning either one first. (PHP and Java are two additional programming languages that can be used for web development, but they aren’t usually recommended for beginners.)

When choosing whether to learn Ruby, Python, or any other programming language, consider the following factors:

  • Domain-specific use: Some languages have better functionality for certain domains and purposes. For example, Python has built-in features and libraries that make it a strong choice for statistics or scientific applications. Ruby is popular among startups because you can quickly create and modify prototypes.
  • Company preference: Companies usually choose one or two programming languages and frameworks with which to develop applications. To find out which languages a company uses, search their website by using www.builtwith.com , review their job postings to see which types of developers they are hiring, or search for blog posts they’ve written about the technology used. For example, Airbnb’s blog post on Large Scale Payment Systems and Ruby on Rails, which is available at nerds.airbnb.com/large-scale-payments-systems-ruby-rails , is a good clue that Ruby on Rails is used at the company. Many companies will hire developers who don’t know the company’s preferred language if the developer is willing to learn it.
  • Feature support: If you’re building an app with a must-have feature, look into how you would build that feature. You can search for online tutorials, how other companies built the same or similar feature, and open source libraries that offer support. For example, the Python libraries NumPy and SciPy make doing data analysis much easier in Python than in Ruby, though in recent years Ruby developers have created SciRuby to bridge this gap.
  • Community: Inevitably, you’ll get stuck while coding and need others to help you make progress. When evaluating the strength of a community around a programming language, see what discussion sites exist, how active they are, and how quickly people respond to questions. In addition, the existence of mailing lists, blog posts, Meetup groups, and conferences all help create a sense of community and support.

tip View a list of Ruby community resources by visiting www.ruby-lang.org/en/community. For a list of Python community resources, go to www.python.org/community.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.82.163