Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore Coding For Dummies ( PDFDrive )

Coding For Dummies ( PDFDrive )

Published by THE MANTHAN SCHOOL, 2021-06-16 08:43:43

Description: Coding For Dummies ( PDFDrive )

Search

Read the Text Version

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. ******************

Part 3 Putting Together a Web Application ******************

IN THIS PART … Plan to bring your first web application to life. Meet the people who help build web applications. Research each component of your first web application. Build your web application with offers based on location. Debug the errors in your first web application. ******************

Chapter 10 Building Your Own App IN THIS CHAPTER Completing a case study using an app Understanding the process of creating an app to solve a problem Discovering the various people that help create an app If you have a dream, you can spend a lifetime … getting ready for it. What you should be doing is getting started. —DREW HOUSTON If you have read (or skimmed) the previous chapters you now have enough HTML, CSS, and JavaScript knowledge to write your own web application. To review, HTML puts content on the web page, CSS styles that content, and JavaScript allows for interaction with that content. You may feel like you don’t have enough coding knowledge to create an app, but I promise that you do. Besides, the only way to know for certain is to get started and try. In this chapter, you come to better understand the app you are going to build, and the basic steps to create that app. Developers often begin with just the information presented in this chapter and are expected to create a prototype. After reading this chapter think about how you would build the app, and then refer to chapters that follow for more details on each step. Building a Location-Based Offer App Technology can provide developers (like you) one of the most valuable pieces of information about your users — their current location. With mobile devices, such as cell phones and tablets, you can even find a user’s location when they are on-the-go. Although you likely have used an app to retrieve the time, weather, or even driving directions, you may never have received an offer on your phone to come into a store while walking down the street or driving in a car. Imagine passing by a Mexican restaurant during lunch time and receiving an offer for a free taco. I’m hungry, so let’s get started! Understanding the situation The following is a fictitious case study. Any resemblance to real companies or events is coincidental. The McDuck’s Corporation is one of the largest fast food restaurants in the world, specializing in selling hamburgers in a restaurant called McDuck’s. The company has 35,000 of these restaurants which serve 6.5 million burgers every day t**o***7***0***m****i*l**lion people in over 100 countries. In

September 2014, McDuck’s experienced its worst sales decline in over a decade. After many meetings, the executive team decided that the key to improving sales would be increasing restaurant foot traffic. “Our restaurant experience, with burger visuals and french-fry aromas, is the best in the industry — once a customer comes in it is a guaranteed sale,” says McDuck’s CEO Duck Corleone. To promote restaurant visits, McDuck’s wants a web application so customers can check-in to their favorite store, and receive an offer or coupon if they are close to a restaurant. “Giving customers who are 5 or 10 minutes away from a restaurant an extra nudge may result in a visit. Even if customers use this app while at the restaurant, this will allow us to maintain a relationship with them long after they have left,” says Corleone. The McDuck Corporation wants to run a pilot to better understand whether location based offers will increase sales. Your task is to: Create an app that will prove whether location based offers are effective. Limit the app to work on just one McDuck’s store of your choice. Obtain the location of customers using the app. Show offers to those customers who are five or ten minutes from the store. McDuck’s currently has a website and a mobile app, but both only show menu and store location information. If this pilot is successful, McDuck’s will incorporate your code into its website and mobile app. Plotting your next steps Now that you understand McDuck’s request, you likely have many questions: What will the app look like? What programming languages will I use to create the app? How will I write code to locate a user’s present location? What offer will I show to a user who is 5 to 10 minutes away? These are natural questions to ask, and to make sure you are asking all the necessary questions upfront in an organized way you will follow a standard development process. Following an App Development Process Building an app can take as little time as an hour or as long as decades. For most startups, the development processes for the initial product prototype averages one or two months to complete, whereas enterprise development processes for commercial grade software takes six months to a few years to complete, depending on the industry and the project’s complexity. A brief overview of the entire process is described here, and then each step is covered in additional detail as you build the app for McDuck’s. ******************

An app can be a software program that runs on desktop or mobile devices. The four steps you will follow when building your app are: Planning and discovery of app requirements Researching of technology needed to build the app, and designing the app look and feel Coding your app using a programming language Debugging and testing your code when it behaves differently than you intended In total, you should plan to spend between two to five hours building this app. As shown in Figure 10-1, planning and research alone will take more than half your time, especially if this is the first time you are building an app. You might be surprised to learn that actually writing code will take a relatively small amount of time, with the rest of your time spent debugging your code to correct syntax and logic errors. ******************

FIGURE 10-1: Time allocated to complete the four steps in the app development process. App development processes have different names, and the two biggest processes are called waterfall and agile. Waterfall is a set of sequential steps followed to create a program, whereas agile is a set of iterative steps followed to create a program. Additional discussion can be found in Chapter 3. Planning Your First Web Application You or your client has a web app idea, and planning is the process of putting those ideas down on paper. Documenting all the features that will go into the app is so important, because as the cartoon in Figure 10-2 shows for web development, and in computer science generally, it can be difficult to understand upfront what features***a**r**e***t*e**c***h**nically easy versus difficult to implement.

FIGURE 10-2: It can be difficult to separate technically easy and difficult projects. The planning phase also facilitates an upfront conversation around time, project scope, and budget, where a common saying is to “pick two out of the three.” In some situations, such as with projects for finance companies, timelines and project scope may be legally mandated or tied to a big client, and cannot be changed, and so additional budget may need to set aside to meet both. In other situations, such as projects for small startups, resources are scarce so it’s more common to adjust the project scope or extend the timeline than to increase the project’s budget. Before writing any code, it will be helpful to understand which dimensions can be flexed and which are fixed. Finally, although you will likely play multiple roles in the creation of this web app, in real life teams of people help bring to life the web apps you use every day. You will see the roles people play, and how everyone works together. Exploring the Overall Process The purpose of the planning phase is to: Understand the client goals: Some clients may want to be the first to enter an industry with an app, even if it means sacrificing quality. Other clients may require the highest standards of quality, reliability, and stability. Similarly, some others may prioritize retaining existing customers, while others want to attract new customers. All these motivations affect the product design and implementation in big and small ways. ******************

If you are a developer in a large company, your client is usually not the end user but whoever in your internal team must greenlight the app before it is released to the public. At many companies, such as Google, Yahoo, and Facebook, most projects do not pass internal review and are never released to the public. Document product and feature requests: Clients usually have an overall product vision, a list of tasks the user must be able to complete with the app. Often, clients have features in mind that would help accomplish those tasks. Agree on deliverables and a timeline: Almost every client will imagine a much bigger product than you have time to build. For a developer, it is extremely important to understand what features are absolutely necessary and must be built, and what features are “nice to have” if there is time remaining at the end of the project. If every feature is a “must have” you need to either push the client to prioritize something, or make sure you have given yourself enough time. Estimating the time to complete software projects is one of the most difficult project management tasks. There is greater variability and uncertainty than physical construction projects, like building a house, or intellectual projects, like writing a memo. The most experienced developers at the world’s best software companies routinely miss estimates, so don’t feel bad if completion takes longer than you think. Your estimation skill will improve with time and practice. After separating the necessary features from the “nice to have,” you should decide which features are easy and which are complex. Without previous experience this might seem difficult, but think about whether other applications have similar functionality. You should also try searching the web for forum posts, or products that have the feature. If no product implements the feature, and all online discussion portray the task as difficult it would be worthwhile agreeing up-front on an alternative. Discuss tools and software you will use to complete the project, and your users will use to consume the project: Take the time to understand your client and user’s workflow to avoid surprises from incompatible software. Web software usually works across a variety of devices, but older operating systems and browsers can cause problems. Defining at the start of the project exactly which browser versions you will support (such as Internet Explorer 9 and later), and which devices (such as desktop and iPhone only) will save development and testing time. Usually, these decisions are based on how many existing users are on those platforms, and many organizations will support a browser version if used by a substantial amount of the user base — usually at least five percent. ******************

Browser incompatibilities are decreasing as the latest desktop and mobile browsers updates themselves, and are now easier to keep up-to-date. Meeting the People Who Bring a Web App to Life You will be able to complete the app in this book by yourself, but the apps you build at work or use every day, like Google Maps or Instagram, are created by teams of people. Teams for a single product can vary in size, reaching upwards of 50 people, and each person plays a specific role across areas like design, development, product management, and testing. In smaller companies, the same person may perform multiple roles, while at larger companies the roles become more specialized and individual people perform each role. Creating with designers Before any code has been written, designers work to create the site look and feel through layout, visuals, and interactions. Designers answer simple questions like “should the navigational menu be at the top of the page or the bottom?” to more complex questions like “how can we convey a sense of simplicity, creativity, and playfulness?” In general, designers answer these types of questions by interviewing users, creating many designs of the same product idea, and then making a final decision by choosing one design. Good design can greatly increase adoption of a product or use of site, and products like Apple’s iPhone and Airbnb.com. (See Figure 10-3.) ******************

FIGURE 10-3: Jonathan Ive, SVP of Design at Apple, is credited for Apple’s design successes. When building a website or app, you may decide you need a designer, but keep in mind within design there are multiple roles that designers play. The following roles are complementary, and may all be done by one person or by separate people: User interface (UI) and user experience (UX) designers deal primarily with “look and feel” and with layout. When you browse a website, for example Amazon, you may notice that across all pages the navigation menus, and content are in the same place, and use identical or very similar font, buttons, input boxes, and images. The UI/UX designer thinks about the order in which screens are displayed to the user, along with where and how the user clicks, enters text, and otherwise interacts with the website. If you eavesdropped on UI/UX designers, you may hear conversation like, “his page is too busy with too many call to actions. Our users don’t make this many decisions anywhere else on the site. Let’s simplify the layout by having just a single Buy button so anyone can order in just one click.” Visual designers deal primarily with cr**e**a**t*i**n**g***t**h**e final graphics used on a website, and is the role most closely associated with “designer.” The visual designer creates final versions of

icons, logos, buttons, typography, images. For example, look at your Internet browser — the browser icon, the Back, Reload, and Bookmark buttons are all created by a visual designer, and anyone using the browser for the first time will know what the icons mean without explanation. If you eavesdropped on visual designers, you may hear conversation like, “The color contrast on these icons is too light to be readable, and if including text with the icon, let’s center-align the text below the icon instead of above it.” Interaction designers deal primarily with interactions and animations based on user input and situation. Initially, interaction design were limited to keyboard and mouse interactions, but today touch sensors on mobile devices have created many more potential user interactions. The interaction designer thinks about how to use the best interaction so the user is able to complete a task as easily as possible. For example, think about how you check your email on your mobile phone. For many years, the traditional interaction was to see a list of messages, click on a message, and then click on a button to reply, flag, folder, or delete the message. In 2013, interaction designers rethought the email app interaction, and created an interaction so users could swipe their finger left or right to delete or reply to email messages instead of having to click through multiple menus. If you eavesdropped on interaction designers, you may hear conversation like, “While users are navigating with our maps app, instead of letting us know they are lost by clicking or swiping, maybe they can shake the phone and we instantly have a location specialist call them.” If creating an app was like making a movie, designers would be screenwriters. Coding with front- and back-end developers After the design is complete, the front-end and back-end developers make those designs a reality. Front-end developers, such as Mark Otto and Jacob Thornton (see Figure 10-4), code in HTML, CSS, and JavaScript, and convert the design into a user interface. These developers write the same code that you have been learning throughout this book, and ensure the website looks consistent across devices (desktop, laptop, and mobile), browsers (Chrome, Firefox, Safari, and so on), and operating systems (Windows, Mac, and so on). All these factors, especially increased adoption of mobile device, result in thousands of combinations that must be coded for and tested because every device, browser, and operating system renders HTML and CSS differently. ******************

FIGURE 10-4: Mark Otto and Jacob Thornton created Bootstrap, the most popular front-end framework. If creating an app was like making a movie, front-end developers would be the starring actors. Back-end developers such as Yukihiro Matsumoto (see Figure 10-5) add functionality to the user interface created by the front-end developers. Back-end developers ensure everything that’s not visible to the user and behind the scenes is in place for the product to work as expected. Back-end developers use server-side languages like Python, PHP, and Ruby to add logic around what content to show, when, and to whom. In addition, they use databases to store user data, and create servers to serve all of this code to the users. ******************

FIGURE 10-5: Yukihiro Matsumoto created Ruby, a popular server-side language used to create websites. If creating an app was like making a movie, back-end developers would be the cinematographers, stunt coordinators, makeup artists, and set designers. Managing with product managers Product managers help define the product to be built, and manage the product development process. When engineering teams are small (such as fifteen people or less) communication, roles, and accountability are easily managed internally without much formal oversight. As engineering teams grows, the overhead of everyone communicating with each other also grows, and without some process can become unmanageable, leading to miscommunication and missed deadlines. Product managers serve to lessen the communication overhead, and when issues arise as products are being built decide whether to extend timelines, cut scope, or add more resources to the team. Product managers are often former engineers, who have a natural advantage in helping solve technical challenges that arise, but non-technical people are also assuming the role with success. Usually, no engineers report to the product manager, causing some to comment that product managers have “all of the responsibility, an*d****n**o**n***e***o**f* the authority.” One product manager wielding great responsibility and authority is Sundar Pichai, who originally was a product

manager for the Google toolbar, and recently was appointed to oversee many of Google’s products, including search, Android, Chrome, maps, ads, and Google+. (See Figure 10-6.) FIGURE 10-6: Sundar Pichai oversees almost every major Google product. Testing with quality assurance Testing is the final step of the journey after an app or website has been built. As a result of the many hands that helped with production, the newly created product will inevitably have bugs. Lists are made of all the core app user tasks and flows, and human testers along with automated programs go through the list over and over again on different browsers, devices, and operating systems to find errors. Testers compile the newly discovered bugs, and send them back to the developers, who prioritize which bugs to squash first. Trade-offs are always made between how many users are affected by a bug, the time it takes to fix the bug, and the time left until the product must be released. The most important bugs are fixed immediately, and minor bugs are scheduled to be fixed with updates or later released. Today, companies also rely on feedback systems and collect error reports from users, with feedback forms and in some cases through automated reporting. ******************

Chapter 11 Researching Your First Web Application IN THIS CHAPTER Dividing an app into smaller pieces, or steps Using code from various sources to perform those steps Creating app designs by reviewing and improving upon existing solutions If we knew what it was we were doing, it would not be called research. —ALBERT EINSTEIN With the basic requirements defined, the next step is researching how to build the application. Apps consist of two main parts: functionality and form (design). For each of these parts, you must: Divide the app into steps: Although it’s good practice to divide anything you are going to build into steps, diving apps into manageable pieces is an absolute necessity for large software projects with many people working across multiple teams. Research each step: When doing your research, the first question to ask is whether you must build a solution yourself or use an existing solution built by someone else. Building your own solution usually is the best way to directly address your need, but it takes time, whereas implementing someone else’s solution is fast but may only meet part of your needs. Choose a solution for each step: You should have all the solutions selected before writing any code. For each step, decide whether you are writing your own code, or using pre-built code. If you are not writing the code yourself, compare a few options so you can pick one with confidence. Dividing the App into Steps The biggest challenge with dividing an app into steps is knowing how big or small to make each step. The key is to make sure each step is discrete and independent. To test whether you have the right number of steps, ask yourself if someone else could solve and complete the step with minimal guidance. Finding your app’s functionality Recall that McDuck’s wants to promote restaurant visits by using a web application that sends customers an offer or coupon if they’re close to a restaurant. To make this job easier, you are to create the app for customers visiting just one store. Your first move is to break down this app i*n**t*o****s**t*e**p**s***needed for the app to function. These steps

should not be too specific: Think of them in broad terms, as if you were explaining the process to a kindergartner. With a pen and paper, write down these steps in order. Don’t worry about whether each step is correct, as your skill will improve with practice and time. To help you start, here are some clues: Assume the McDuck’s app activates when the customer presses a button in the app to check-in to a store. When the button is pressed, what are the two locations that the app must be aware of? When the app is aware of these two locations, what calculation involving these two locations must the computer make? After computing this calculation, what effect will the computer show? Fill out your list now, and don’t continue reading until you’ve completed it. Finding your app’s functionality: My version The following is my version of the steps needed to make the app function according to McDuck’s specifications. My steps may differ from yours, of course, and this variation is completely fine. The important lesson here is that you understand why each of these steps is necessary for the app to work: 1. The customer presses a button on the app. The instructions above said to initiate the app with the press of a button. That being said, there are two other options for launching the app: Executing the steps continuously in the background, regularly checking the customer’s location. Currently, this technique places a heavy drain on the battery, and is not usually recommended. Executing the steps only when the customer opens the app. 2. After the button is pressed, find the customer’s current location. The customer’s location is one of the two locations you need to identify. The customer’s current location is not fixed, and it changes, for example, when the customer is walking or driving. 3. Find the fixed location of a McDuck’s store. The McDuck’s restaurant location is the other location you need to identify. Because this is a pilot, you only need to identify the location for one McDuck’s restaurant, a fixed location that will not change. Hypothetically, assuming that the pilot is successful and that McDuck’s wants to implement this app for users visiting all 35,000 restaurants, you’d have to track many more restaurant locations. Additionally, in a larger rollout the locations would need to be updated regularly, as new restaurants open, and as existing restaurants move or close. 4. Calculate the distance between the customer’s current location and the McDuck’s restaurant, and name this distance Cu**s**t**o**m****e**r***D* istance.

This step calculates how far away the customer is from the McDuck’s restaurant. One complexity to be aware of — but not to worry about right now — is the direction in which the customer is moving. Although McDuck’s did not specify whether they want to display offers to customers heading both toward and away from their store, this may be a question worth asking anyway. 5. Convert five to ten minutes of customer travel into a distance called Threshold Distance. McDuck’s CEO Duck Corleone wants to target customers who are five to ten minutes away from the store. Distance, in this sense, can be measured in both time and in units of distance such as miles. For consistency, however, plan to convert time into distance — translate those five to ten minutes into miles. The number of miles traveled in this time will vary by common mode of transportation and by location, because five to ten minutes of travel in New York City won’t get you as far as five to ten minutes of travel in Houston, Texas. 6. If the Customer Distance is less than the Threshold Distance, then show an offer to the customer. Following McDuck’s specifications, the app should attract customers to come to the store, and so the app only shows offers to customers who are close to the restaurant. Another complexity to be aware of — but not to worry about right now — is that the Customer Distance can change quickly. Customers traveling by car could easily be outside the Threshold Distance one minute and inside it the next. Figure 11-1 shows the customers we want to target, relative to a fixed restaurant location. ******************

FIGURE 11-1: Customers we want to target based on a fixed restaurant location. Many software logic mistakes happen at this stage, because the programmer forgets to include a step. Take your time reviewing these steps and understanding why each step is essential, and why this list of steps is the minimum necessary to operate the app. Finding your app’s form After you settle on what the app will do, you must find the best way to present this functionality to users. There are many ways that users can interact with your app’s functionality, so picking out the right approach can be tricky. Designing an app can be fun and rewarding, but it’s hard work. After the first iteration of an app’s design, developers are often disappointed: Users will rarely use the product as intended and will find many parts of the app confusing. This is natural — especially because at this stage you’re often creating something or having the user do something that hasn’t been done before. Your only choice is to keep trying, to keep testing, modifying, and creating new designs until your app is easy for everyone to use. Although the iPod is a hardware product, the approach Apple took to perfect it is basically the same. Figure 11-2 shows how the design can change over time, with the button layout changing from the original click-wheel to individual horizontal buttons, and finally back to the cl**i*c**k**-**w****h**e**e* l again.

FIGURE 11-2: Apple’s iPod design changes over multiple product releases. The following list describes a basic design process to create the look and feel of your app: 1. Define the main goals of your app. If you were at a party, and you had to explain what your app did in one sentence, what would it be? Some apps help you hail a taxi, reserve a table at a restaurant, or book a flight. Famously, the goal for the iPod was 1,000 songs in your pocket accessible within three clicks, which helped create an easy to use user interface. An explicitly defined goal will serve as your north star, helping you to resolve questions and forcing you to keep trying. 2. Break these goals into tasks. Each goal is the sum of many tasks, and listing them will help you design the shortest path to completing each task and ultimately the goal. For instance, if your app’s goal is for a user to book a flight, then the app will likely need to record desired flying times and destinations, search and select flights departing during those times, record personal and payment information, present seats for selection, and confirm payment of the flight. Sometimes designers will segment tasks by user persona, another name for the person completing the task. For example, this app may be used by business and leisure travelers. Leisure travelers may need to do heavy searching and pick flig**h***t*s***b**a**s**e***d on price, while business travelers mostly rebook completed flights and pick flights based on schedule.

3. Research the flows and interactions necessary to accomplish these tasks. For example, our flight app requires the user to select dates and times. One immediate question is whether the date and time should be two separate fields or one field, and on a different or same screen as the destination. Try to sketch what feels intuitive for you, and research how others have solved this problem. You can use Google to find other travel apps, list all the various designs, and either pick or improve upon the design you like best. Figure 11-3 shows two different approaches to flight search. Similarly, you can also use design-centric sites, such as www.dribbble.com, to search designer portfolios for features and commentary. 4. Create basic designs, called wireframes, and collect feedback. Wireframes, as shown in Figure 11-4, are low fidelity website drawings which show structurally how site content and interface interact. Wireframes are simple to create, but should have enough detail to elicit feedback from others. Many wireframe tools use a simple almost pencil-like drawing to help anyone providing comments to focus on the structural and bigger picture design, instead of smaller details like button colors or border thicknesses. Feedback at this stage to refine design is so important because the first wireframe likely does not address users’ main concerns and overcomplicates the tasks a user needs to do. With mobile devices increasing in popularity relative to desktop devices, remember to create mobile and desktop versions of your wireframes. 5. Create mock-ups and collect more feedback. (See Figure 11-5.) After you have finished talking to your client and to users, it is time to create mock-ups, which are high fidelity website previews. These designs have all the details a developer needs to create the website including final layout, colors, images, logos, and sequences of screens to show when the user interacts with the web page. After creating a mock-up, plan to collect more feedback. Collecting feedback at every stage of the design process might seem unnecessary, but it is much easier to explore different designs and make changes before any code has been written. 6. Send the final file to the developers. After the mock-up has been created and approved, you typically send a final image file to the developer. Although this file could be in any image file format like PNG or JPG, the most popular file format used by designers is PSD, created using Adobe Photoshop. ******************

FIGURE 11-3: Different designs for flight reservation from Hipmunk.com and United Airlines. FIGURE 11-4: A wireframe for an email client. FIGURE 11-5: A mock-up for an email client. ****************** Finding your app’s form: The McDuck’s Offer App design

In this section you follow the design process described in the previous section to create a simple design for the McDuck’s Offer app. As part of the design, you should do the following things: 1. Define the main goals of your app. The main goal for McDuck’s is to use offers to attract customers to restaurants. 2. Break these goals into tasks. Customers need to view the offer, navigate to the store, and use the offer. 3. Research the flows and interactions needed to accomplish these tasks. Because this is the first iteration of the app, let’s focus on just allowing the customer to view the offer. One function that McDuck’s did not specify is the ability to save single-use coupons and to share general-use coupons. However, when looking at other apps, like the ones in Figure 11-6, the need for this becomes more obvious. Also, some similar apps allow the customer to spend money to buy coupons — maybe this functionality should be added as well. These questions would be great to present to McDuck’s later. The apps in Figure 11-6 also all display various “call to action” buttons to the user before displaying the deal. Some apps ask the user to check-in to a location, other apps ask the user to purchase the coupon, and still others show a collection of new or trending coupons today. For now, and to keep things simple, let’s assume that our McDuck’s app has a button that allows customers to check-in to their favorite McDuck’s location, and when clicked within the target distance the app displays a general-use coupon that customers receive for free. 4. Create basic designs, called wireframes, and collect feedback. A sample design for the app, based on the look and feel of other apps, appears in Figure 11-7. 5. Create mock-ups and collect more feedback. Ordinarily, you would create mock-ups, which are more polished designs with real images, from the wireframes and present them to customers for feedback. In this case, however, the app is simple enough that you can just start coding. FIGURE 11-6: Example flow from deals and offer apps currently in the market. ******************

FIGURE 11-7: A sample wireframe for the McDuck’s offer app. Identifying Research Sources Now that you know what your app will do, you can focus on how your app will do it. After breaking down your app into steps, you go over each step to determine how to accomplish it. For more complicated apps, developers first decide which of these two methods is the best way to complete each step: Building code from scratch: This is the best option if the functionality in a particular step is unique or strategically important, an area of strength for the app, and existing solutions are expensive or non-existent. With this option, you and developers within the company write the code. Buying or using a pre-existing solution: This is the best option if the functionality in a particular step is common, non-core technical area for the app, and existing solutions are competitively priced. With this option, you and developers working on the app use code written by external third party developers. One company that recently made this decision — publicly and painfully — is Apple with its Maps product. In 2012, after years of using Google Maps on its mobile devices, Apple decided to introduce its own maps application that it had been developing for two years. Although the Maps product Apple built internally turned out to initially be a failure, Apple decided to build its own mapping application because it viewed mapping capabilities as strategically important and because turn-by-turn navigation solutions w**e**r**e***n**o**t***a**vailable in the solution provided by Google.

Whether you’re building or buying, research is your next step. Here are some sources to consider when researching: Search engines: Use Google.com or another search engine to type in what you are trying to accomplish with each step. One challenge can be discovering how the task you’re trying to achieve is referred to by programmers. For instance, if I want to find my current location, I might enter show my location in an app into a search engine, but this results in a list of location-sharing apps. After reading a few of the top ten results, I see that location-tracking is also referred to as geolocation. When I search again for geolocation the top results include many examples of code that shows my current location. For more generic searches for code examples, try including the name of the computer language and the word syntax. For example, if you want to insert an image on a web page, search for image html syntax to find code examples. Prior commercial and open-source apps: Examining how others built their apps can give you ideas on how to improve upon what already exists, and insight into pushing existing technology to the limit to achieve an interesting effect. For instance, say you wanted to build a mobile app that recognized TV ads from the “audio fingerprint” of those ads and directed viewers to a product page on a mobile device. To create this app, you could build your own audio fingerprinting technology, which would likely take months or longer to build, or you could partner with Shazam, a commercial application, or Echoprint, an open-source music fingerprinting service. Either app can record a 10 to 20-second audio sample, create a digital fingerprint after overcoming background noise and poor microphone quality, compare the fingerprint to large audio database, and then return identification information for the audio sample. Industry news and blogs: Traditional newspapers, like the Wall Street Journal, and tech blogs, like TechCrunch.com, report on the latest innovations in technology. Regularly reading or searching through these sites is a good way to find others who have launched apps in your space. API directories: You can easily search thousands of APIs for the functionality you need to implement. For example, if you were creating an app that used face recognition instead of a password, you could search for face detection APIs and use an API you find instead of trying to build a face detection algorithm from scratch. Popular API directories include www.programmableweb.com and www.mashape.com. As discussed in Chapter 9, APIs are a way for you to request and receive data from other programs in a structured, predictable, documented way. User-generated coding websites: Dev*e***l*o**p***e**r**s***i*n different companies frequently face the same

questions on how to implement functionality for features. Communities of developers online talk about shared problems and contribute code so anyone can see how these problems have been solved in the past. You can participate in developer conversation and see the code other developers have written by using www.stackoverflow.com and www.github.com. Researching the Steps in the McDuck’s Offer App To implement the functionality in the McDuck’s Offer app, you broke down the app into six steps using plain English. Now, research how you can convert those steps into code using the resources listed in the previous section. Your app will require HTML to put content on the page, CSS to style that content, and JavaScript for the more interactive effects. Do your best to research each of the steps on your own, write down the answers, and then look over the suggested code in the next section: “The customer presses a button on the app:” This code creates a button that triggers every subsequent step. Creating a button on a web page is a very common task, so to narrow down the results search for html button tag. Review some of the links in the top 10 search results, and then write down the HTML tag syntax to create a button that says “McDuck’s Check-in.” In your search results, sites like w3schools.com are designed for beginners, and will include example code and simple explanations. “After the button is pressed, find the customer’s current location:” In web lingo, finding a user’s location is called geolocation. I will provide you with JavaScript geolocation code, along with an explanation for how it works and where I found it. To trigger this JavaScript code, you need to add an attribute to the HTML button tag to call a JavaScript function named getlocation(). As described in Chapter 4, HTML attributes are inserted in the opening HTML tag. Search for html button javascript button on click to find out how to insert the onclick attribute to your button HTML code. Review the search results, and then write down the HTML syntax for your button code. “Find the fixed location of a McDuck’s store:” You’ll need a real-world address to serve as the McDuck’s store. Use a mapping application like maps.google.com to find the street address of a burger restaurant near you. Computers typically represent physical addresses using latitude and longitude numbers instead of street addresses. You can search for websites that convert street addresses into latitud*e****a**n**d****l*o***n*gitude numbers, or if you’re using Google Maps, you can find the numbers in the URL, as shown in Figure 11-8. The first number after

the @ sign and up to the comma is the latitude, and the second number between the two commas is the longitude. Figure 11-8 shows a McDonald’s store in New York City, and the latitude is 40.7410344, and the longitude is –73.9880763. Track down the latitude and longitude numbers for the burger restaurant of your choice, up to seven decimal places, and write them down on a piece of paper. Include a negative sign if you see one, and all seven decimal places for the greatest accuracy. “Calculate the distance between the customer’s current location and the McDuck’s restaurant, and name this distance Customer Distance:” Latitude and longitude are coordinates that represent a location on a sphere. The distance along the surface of the sphere between two sets of latitude and longitude coordinates is calculated using the Haversine formula. You can find a JavaScript version of the formula at stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two- latitude-longitude-points. This is the formula you will use to calculate distance when creating the McDuck’s app, and I will include this code for you. Don’t get bogged down in the details of how the Haversine formula works. Abstraction is an important concept to remember when programming, and this basically means that as long as you understand the inputs to a system, and the outputs, you don’t really need to understand the system itself, much as you don’t need to understand the mechanics of the internal combustion engine in order to drive a car. “Convert five to ten minutes of customer travel into a distance called Threshold Distance:” Using the most common method of transportation in your current city, write down the number of miles you could you travel, on average, in five to ten minutes. “If the Customer Distance is less than the Threshold Distance then show an offer to the customer:” The two pieces to research for this step are the conditional statement that decides when to show the offer to the consumer, and the actual offer: The conditional statement: This is written in JavaScript using an if-else statement. If the customer is within the threshold distance, then it shows the offer; otherwise (else) it shows another message. To review the if-else syntax, search Google or another search engine for JavaScript if-else statement syntax (or refer to Chapter 9 to review the coverage of the if-else statement syntax there). The offer to show to the consumer: The easiest way to show an offer is to use the JavaScript alert(). Search for JavaScript alert syntax. After you’ve conducted your searches, write down your if-else statement with a text alert() for a free burger if the custome***r***i*s***w****i*t*h**in the Threshold Distance, and a text alert() notifying the customer they have checked in.

When you have the if-else statement working, you can replace the text alert() with an image. Search http://images.google.com for a burger coupon image. After you find the image, left-click on it from the image grid in the search results, and left-click again on View Image button. When the image loads the direct link to the image will be in the URL address bar in the browser. The code to insert the image is shown in Chapter 4. FIGURE 11-8: Latitude and longitude of a McDonald’s in New York City. Choosing a Solution for Each Step With your research finished, it’s time to find the best solution. If multiple solutions exist for each step, you now need to choose one. To help you choose, weigh each of your multiple solutions across a variety of factors, such as these: Functionality: Will the code you write or pre-built solution you found do everything you need? Documentation: Is there documentation for the pre-built solution, like instructions or a manual, that is well written with examples? Community and support: If something goes wrong while writing your code, is there a community you can turn to for help? Similarly, does the pre-built solution have support options you can turn to if needed? ****************** Ease of implementation: Is implementation as simple as copying a few lines of code? Or is a

more complex setup or an installation of other supporting software necessary? Price: Every solution has a price, whether it is the time spent coding your own solution or the money paid for someone else’s pre-built code. Think carefully about whether your time or money is more important to you at this stage. The following are suggested solutions for the previous McDuck’s Offer app research questions. Your answers may vary, so review each answer to see where your code differs from mine: “The customer presses a button on the app:” The HTML tag syntax to create a button that says “McDuck’s Check-in” is: <button>McDuck's Check-in</button> The syntax for an HTML button is available here www.w3schools.com/tags/tag_button.asp. “After the button is pressed, find the customer’s current location:” The HTML syntax for your button code is: <button onclick=\"getLocation()\">McDuck's Check-in</button> The syntax for calling a JavaScript function by pressing a button is available here www.w3schools.com/jsref/event_onclick.asp. “Find the fixed location of a McDuck’s store:” I picked a McDonald’s store in New York City near Madison Square Park whose latitude is 40.7410344 and longitude is –73.9880763. The latitude and longitude for your restaurant, of course, will likely differ. “Calculate the distance between the customer’s current location and the McDuck’s restaurant, and name this distance Customer Distance:” The following is the actual code for the Haversine formula, used to calculate the distance between two location coordinates, found on Stackoverflow at stackoverflow.com/questions/27928/how-do-i-calculate- distance-between-two-latitude-longitude-points, I modified this code slightly so that it returned miles instead of kilometers: function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) { var R = 6371; // Radius of the earth in km var dLat = deg2rad(lat2-lat1); // deg2rad below var dLon = deg2rad(lon2-lon1); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon/2) * Math.sin(dLon/2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c * 0.621371; // Distance in miles return d; ****************** }

function deg2rad(deg) { return deg * (Math.PI/180); } An explanation of how this formula works is outside the scope of this book, but make sure you understand the formula’s inputs (latitude and longitude) and the output (distance between two points in miles). “Convert five to ten minutes of customer travel into a distance called Threshold Distance:” In New York City, people usually walk, so traveling for five to ten minutes would take you 0.5 miles, which is my Threshold Distance. “If the Customer Distance is less than the Threshold Distance, then display an offer to the customer:” The syntax for the if-else statement with the two text alert() methods is: If (distance < 0.5) { alert(\"You get a free burger\"); } else { alert(\"Thanks for checking in!\"); } The syntax for a JavaScript if-else statement is available at www.w3schools.com/js/js_if_else.asp. ******************

Chapter 12 Coding and Debugging Your First Web Application IN THIS CHAPTER Reviewing code to see pre-existing functionality Writing code by following steps to create your app Debugging your code by looking for common syntax errors Talk is cheap. Show me the code. —LINUS TORVALDS It may not feel like it, but you’ve already done the majority of work toward creating your first web application. You painfully broke down your app into steps, and researched each step to determine functionality and design. As Linus Torvalds, creator of the Linux operator system, said, “Talk is cheap.” So let’s start actually coding. Getting Ready to Code Before you start coding, do a few housekeeping items. First, ensure that you are doing all of the following: Using the Chome browser: Download and install the latest version of Chome, as it offers the most support for the latest HTML standards, and is available for download at www.google.com/chrome/browser. Working on a desktop or laptop computer: Although it is possible to code on a mobile device, it can be more difficult and all layouts may not appear properly. Remembering to indent your code to make it easier to read: One main source of mistakes is forgetting to close a tag or curly brace, and indenting your code will make spotting these errors easier. Remembering to enable location services on your browser and computer: To enable location services within Chrome, click on the settings icon (3 horizontal lines on the top right of the browser), and click on Settings. Then click on the Settings tab, and at the bottom of the screen click on “Show Advanced settings … ” Under the Privacy menu heading, click on “Content settings … ” and scroll down to Location and make sure that “Ask when a site tries to track your physical location” is selected. You can read more here: support.google.com/chrome/answe*r**/***1**4**2***0**6***5.

To enable location services on a PC no additional setting is necessary, but on a Mac using OS X Mountain Lion or later, from the Apple menu choose System Preferences, then click on the Security & Privacy icon, and click the Privacy tab. Click the padlock icon on the lower left, and select Location Services, and check Enable Location Services. You can read more here: support.apple.com/en-us/ht5403. Finally, you need to set up your development environment. To emulate a development environment without instructional content use Codepen.io. Codepen.io offers a free stand-alone development environment, and makes it easy to share your code. Open this URL in in your browser: codepen.io/nabraham/pen/ExnsA. Coding Your First Web Application With the Codepen.io URL loaded, let us review the development environment, the pre-written code, and the coding steps for you to follow. Development environment The Codepen.io development environment, as shown in Figure 12-1, has three coding panels, one each for HTML, CSS, and JavaScript. There is also a preview pane to see the live results of your code. Using the button at the bottom of the screen, you can hide any coding panel you aren’t using, and the layout of the coding panels can be changed. Signing up for a Codepen.io account is completely optional, and allows you to fork or save the code you have written, and share it with others. ****************** FIGURE 12-1 The Codepen.io development environment.

Pre-written code The Codepen.io development environment includes some pre-written HTML, CSS, and JavaScript code for the McDuck’s app. The pre-written code includes code you have seen in previous chapters, and new code that is explained below: HTML: The HTML code for the McDuck’s app is below, and includes Two sections: an opening and closing <head> tag, and an opening and closing <body> tag. Inside the <body> tags are <h1> tags to create a heading and <div> tags. Additional <div> tags to display messages created in the JavaScript file. The <div> tag is a container that can hold content of any type. The first <div> tag is used to display your current longitude and latitude. The second <div> tag can be used to display additional content to the user. Instructions to insert the HTML button and onclick attribute code, which you researched in previous chapters. Here’s the HTML code: <!DOCTYPE html> <html> <head> <title>McDuck's App</title> </head> <body> <h1> McDuck's Local Offers</h1> <!--1. Create a HTML button that when clicked calls the JavaScript getLocation() function --> <!--Two containers, called divs, used to show messages to user --> <div id=\"geodisplay\"/> <div id=\"effect\"/> </body> </html> CSS: The CSS code for the McDuck’s app is below, and includes: Selectors for the body, heading, and paragraph tags. Properties and values that set the text alignment, background color, font family, font color, and font size. Once your app is functioning, style the app by adding a McDuck’s color scheme and background image logo. Here’s the CSS: body { text-align: center; background: white; } h1, h2, h3, p { ****************** font-family: Sans-Serif; color: black;

} p{ font-size: 1em; } JavaScript: The JavaScript code for the McDuck’s app is below. This pre-written code is a little complex, because it calculates the current location of the user using the HTML Geolocation API. In this section I review the code at a high level so you can understand how it works and where it came from. The Geolocation API is the product of billions of dollars of research and is available to you for free. The most recent browsers support geolocation, though some older browsers do not. At a basic level, code is written to ask whether the browser supports the Geolocation API, and, if yes, to return the current location of the user. When called, the Geolocation API balances a number of data inputs to determine the user’s current location. These data inputs include GPS, wireless network connection strength, cell tower and signal strength, and IP address. With this in mind, let’s look at the JavaScript code. The JavaScript code includes two functions, as follows: The getLocation() function: This function determines whether the browser supports geolocation. It does this by using an if statement and navigator.geolocation, which is recognized by the browser as part of the Geolocation API and which returns a true value if geolocation is supported. Here is the getLocation() function: function getLocation() { if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showLocation); } } The showLocation() function: When the browser supports geolocation, the next step is to call the showlocation function, which calculates and displays the user’s location. And here is the showLocation() function: function showLocation(position){ // 2. Hardcode your store location on line 12 and 13, and update the comment to reflect your McDuck's restaurant address // Nik's apt @ Perry & W 4th St (change to your restaurant location) var mcduckslat=40.735383; var mcduckslon=-74.002994; // current location var currentpositionlat=position.coords.latitude; var currentpositionlon=position.coords.longitude; // calculate the distance between current location and McDuck's location var distance=getDistanceFromLatLonInMiles(mcduckslat, mcduckslon,currentpositionlat,currentpositionlon); // Displays the location using****.*i**n**n*e**r**H*T**M*L property and the lat & long coordinates for your current location document.getElementById(\"geodisplay\").innerHTML=\"Latitude: \" + currentpositionlat + \"

<br>Longitude: \" + currentpositionlon; } // haversine distance formula The rest omitted for brevity because it's shown in a previous chapter The showLocation() function performs the following tasks: Assigns the McDuck longitude and latitude to mduckslat and mcduckslon (Lines 12 and 13 of the code). Assigns the longitude and latitude of the customer’s current location to currentpositionlat and currentpositionlon (Lines 16 and 17 of the code). Calculates the distance in miles between those two points and assigns that distance to a variable called distance (Line 20 of the code). The Haversine formula calculates the distance between two points on a sphere, in this case the earth, and the code is shown online but omitted here for brevity. After the button is clicked, the getElementByID and .innerHTML methods display the customer’s current longitude and latitude in an HTML tag named “geodisplay” using the id attribute. JavaScript functions are case-sensitive, so getLocation() differs from getlocation(). The letter L is uppercase in the first function, and lowercase in the second function. Similarly, showLocation() differs from showlocation() for the same reason. Coding steps for you to follow With some of the code already written, and with research in the previous chapter, follow these steps to insert the code: 1. Insert the HTML button code below with onclick attribute calling the getLocation() function after line 8 in the HTML file. <button onclick=\"getLocation()\">McDuck's Check-in</button> After you insert this code, press the button. If your location settings are enabled and you inserted the code properly, you will see a dialog box asking for your permission to share your computer’s location. As shown in Figure 12-2, look at the top of your browser window and click Allow. 2. Update lines 12 and 13 in the JavaScript file with the latitude and longitude of the restaurant near you serving as the McDuck’s store. After you have updated the location, make sure to change the comment in line 10 to reflect the address of your restaurant (instead of my apartment). 3. Add an alert that displays the distance between your location and the restaurant. The distance variable stores the miles from your current location to the restaurant. Make a rough estimate — or use a map for grea*t*e**r***p***r*e**c***i*s* ion — of your current distance from the

restaurant you picked. Then using an alert, show the distance by inserting this code below in line 23. alert(distance); If the distance in the alert is larger or smaller than you expected, you likely entered in incorrect values for the latitude or longitude. If the distance matches your estimate, insert two slashes (\"//\") before the alert and comment it out. 4. Write an if-else statement on line 26 to show an alert if you are within your threshold distance to the restaurant. My code, based on a half-mile threshold distance, is displayed below — yours may vary depending on your alert text and threshold distance. (See Figure 12-3.) if (distance < 0.5) { alert(\"You get a free burger\"); } else { alert(\"Thanks for checking in!\"); } When your app logic is working, you can change alert(\"You get a free burger\"); to an actual picture of a coupon or burger. To do so, replace the entire line the alert is on with the following code: document.getElementById(\"effect\").innerHTML=\"<img src='http://www.image.com/image.jpg'>\"; Replace the URL after src and within the single quotes to your own image URL. Be sure to keep the double quotation marks after the first equals sign and before the semi-colon, and the single quotation marks after the second equals sign and before the right angle bracket. 5. (Optional) When the app is working, change the text colors and insert background images to make the app look more professional. Use hex-values or color names, as discussed in Chapter 6, to change the text and background colors. Additionally, you can insert a background image, as you did in the Codecademy About You exercise, using the following code (see Figure 12-4): background-image: url(\"http://www.image.com/image.jpg\"); ******************

FIGURE 12-2: The browser asks for your permission before sharing your location. FIGURE 12-3: The McDuck’s app displaying an offer to come to the store. ******************

FIGURE 12-4: The completed McDuck’s app with styled content displaying an image to the user. Debugging Your App When coding your app, you will almost inevitably write code that does not behave as you intended. HTML and CSS are relatively forgiving, with the browser even going so far as to insert tags so the page renders properly. However, JavaScript isn’t so forgiving, and the smallest error, such as a missing quotation mark, can cause the page to not render properly. Errors in web applications can consist of syntax errors, logic errors, and display errors. Given that we worked through the logic together, the most likely culprit causing errors in your code will be syntax related. Here are some common errors to check when debugging your code: Opening and closing tags: In HTML, every opening tag has a closing tag, and you always close the most recently opened tag first. Right and left angle brackets: In HTML, every left angle bracket < has a right angle bracket >. Right and left curly brackets: In CSS and JavaScript, every left curly bracket must have a right curly bracket. It can be easy to accidentally delete it or forget to include it. Indentation: Indent your code and use plenty of tabs and returns to make your code as readable as possible. Proper indentation will make it easier for you to identify missing tags, angle brackets, and curly brackets. Misspelled statements: Tags in any language can be misspelled, or spelled correctly but not ****************** part of the specification. For example, in HTML, <img scr=\"image.jpg\"> is incorrect

because scr should really be src for the image to render properly. Similarly, in CSS font- color looks like it is spelled correctly but no such property exists. The correct property to set font color is just color. Keep these errors in mind when debugging — they may not solve all your problems, but they should solve many of them. If you have tried the steps above and still cannot debug your code, tweet me at @nikhilgabraham and include the #codingFD hashtag and your Codepen.io URL in your tweet. ******************

Part 4 Developing Your Coding Skills Further ******************

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 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. 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. ******************

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. 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. Programming languages can do the same set of tasks, and understanding the set of tasks in one language makes it easier to unders*t*a***n**d***t**h**e***n* ext 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 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) TABLE 13-2 Common Ruby Number Methods Method Name Description ****************** Result Example

.abs Returns the absolute value of a number -99.abs 99 .round(ndigits) Rounds a number to n digits 3.1415.round(2) 3.14 .floor Rounds down to the nearest integer 4.7.floor 4 .ceil Rounds up to the nearest integer 7.3.ceil 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 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. 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. 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. TABLE 13-3 Common Ruby Escape Sequences Special Character Description Example ****************** Result \\' or \\\" Quotation marks print \"You had me at \\\"Hello\\\"\" You had me at \"Hello\"

\\t Tab print \"Item\\tUnits \\tPrice\" Item Units Price Anheuser? \\n Newline print \"Anheuser?\\nBusch?\\n Bueller? Bueller?\" Busch? Bueller? Bueller? 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 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. 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. TABLE 13-4 Common Ruby Comparison Operators Type Operator Description ****************** Example

Less than < Evaluates whether one value is less than another value x < 55 Greater than > Evaluates whether one value is greater than another value x > 55 Equality == Evaluates whether two values are equal x == 55 Less than or equal to <= Evaluates whether one value is less than or equal to another value x <= 55 Greater than or equal to >= Evaluates whether one value is greater than or equal to another value x >= 55 Inequality != Evaluates whether two values are not equal x != 55 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!” FIGURE 13-1: An if-else statement with an elsif. 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 called full_name: print \"What's your full name?\" ****************** full_name = gets

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 *s**t*r**i*n**g***s*,***a**nd includes many built-in methods that make processing strings easier in Ruby than in other languages.


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook