Skip to content
100644 535 lines (371 sloc) 28.6 KB
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
1 ---
2 layout: page
3 title: Ruby in 100 Minutes
4 ---
6 Ruby was written to make the programmer's job easy and not care if the computer's job is hard. In this brief introduction we'll look at the key language features you need to get started.
8 1. Instructions and Interpreters
9 2. Variables
10 3. Methods
11 4. Strings
12 5. Numbers
13 6. Symbols
14 7. Collections
15 * Arrays
16 * Hashes
17 8. Conditionals
18 * Conditional Decisions
19 * Conditional Looping
20 9. Nil & Nothingness
bab5a66 @jcasimir Updating HTML
jcasimir authored
22 <div class="note">
23 <p>If you haven't already setup Ruby, visit <a href="/topics/environment/environment.html">the environment setup page for instructions</a>.</p>
24 </div>
873674f @jcasimir Contribution notes
jcasimir authored
26 <div class="note">
27 <p>This tutorial is open source. If you notice errors, typos, or have questions/suggestions, please <a href="">submit them to the project on Github</a>.</p>
28 </div>
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
30 ## Ruby History
32 Ruby is thought of by many as a "new" programming language, but it actually was released in 1994 by a developer known as Matz. Matz is a self-described "language geek" and was a particularly big fan of Perl. His idea for Ruby was to create a language that was flexible and powerful like Perl, but more expressive in its syntax -- even pushing towards English-like readability.
34 Ruby was released in '94 and it grew an audience quickly -- in Japan. Until 2000 there really wasn't any documentation about the language that wasn't in Japanese, so if you wanted to learn Ruby you were pretty much on your own. Dave Thomas, a pioneer of agile programming, became enamored with Ruby and decided to create that documentation. He wrote what's affectionately known as "The Pickaxe", due to its cover image, which opened Ruby to the English-speaking world.
36 From there Ruby started growing, though slowly. It became popular with system administrators to write maintenance and "glue" scripts -- the kinds of things Perl had been used for. The US Ruby community numbered in the hundreds from 2000-2005.
38 In 2004-2005 a Chicago company named 37Signals hired a young CS student to build a web application. They gave him almost total freedom for the implementation; they were only concerned with the design and functionality from the client-side. At the time the predominant web technologies were PHP, Java's JSP, and Microsoft's ASP. They were each somewhat painful, so David, today known as DHH, went his own direction.
40 He wrote the application is Ruby. He relied on the core language and a handful of helper libraries, but more-or-less created the entire stack himself. He and 37Signals worked on the web app, today known as Basecamp, and released it.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
42 Then, once Basecamp was built, DHH extracted the web framework out of it. This was a very different approach from Java or Microsoft where the web frameworks were handed down from on high and the "real world" had to adapt. Instead, Rails was extracted from the real world. It tried to solve only the necessary problems and defer developing features until they were necessary.
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
44 That approach was a big hit and Rails has powered the growth of the Ruby community ever since. Now we have pages and pages of books on Amazon, dozens of conferences around the world, and thousands of people employed as Ruby/Rails developers at organizations like AT&T, NASA, Google, and GroupOn.
46 And if you want to learn Rails, you need to learn Ruby first! Here goes...
48 ## 1. Instructions & Interpreters
50 There are two ways to run Ruby code. You can write one or more instructions in a file then run that file through the Ruby interpreter. When you're writing a "real" program, this is the way to do it. We might have a file named `my_program.rb` like this:
52 ```ruby
53 class Sample
54 def hello
55 puts "Hello, World!"
56 end
57 end
59 s =
60 s.hello
61 ```
63 Then we could run the program like this:
65 ```
66 ruby my_program.rb
67 ```
dfff296 @jcasimir Fixing a few layout bugs
jcasimir authored
69 Ruby is called a scripting language or an interpreted language because it doesn't run on the computer's hardware directly, it first goes through the Ruby interpreter. When you run `ruby my_program.rb` you're actually loading the `ruby` program which in turn loads your `my_program.rb`.
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
71 The second option is to use the Interactive RuBy shell -- IRB. When I'm programming I always have IRB open. IRB has all the same features as the regular Ruby interpreter, but it allows you to easily evaluate one or a handful of instructions and instantly see their results. I use IRB mostly for experimenting. In a regular program I might write a hundred lines of instructions. But if there's one thing I'm not sure about I'll flip over to IRB to test it out. Start IRB by opening a Terminal (Mac) or Command Prompt (Win) and typing `irb`.
73 ## 2. Variables
75 Everything needs a name so we can refer to it. A variable, like in math, is just a name for a piece of data. In Ruby variables are very flexible and can be changed at any time. Variables are assigned using a single equals sign (`=`) where the *right* side of the equals sign is evaluated first, then the value is assigned to the variable named on the *left* side of the equals. Go into IRB, enter in these example instructions, and observe the output that Ruby gives you back:
77 ```ruby
78 a = 5
79 b = 10 + 5
80 c = 15 + a + b
81 b = c - a
82 d = "Hello, "
83 e = "World!"
84 f = d + e
85 g = d*a + e
86 b = "hi!" * b
87 ```
89 The first few lines are simple if you've worked with any programming language before, but the last few get interesting when combining strings and numbers.
91 ## 3. Objects, Attributes, and Methods
93 In Ruby, everything is an object. Objects know information, called _attributes_, and they can do actions, called _methods_.
95 For an example of an object, think about you as a human being. You have attributes like height, weight, and eye color. You have methods like "walk", "run", "wash dishes", and "daydream." Different kinds of objects have different attributes and methods. In the next sections we'll look at a few specific kinds of objects common in Ruby.
97 A class is an *abstract* idea, it defines what all objects of that type can know and do. Think of the chair you're sitting in. It's not an abstract chair, it is an actual chair. We'd call this actual chair an *instance* - it is a realization of the idea chair. It has measurable attributes like height, color, weight. The *class* chair, on the other hand, has an abstract weight, color, and size -- we can't determine them ahead of time.
99 In Ruby we define an object using the `class` keyword, here's an example defining the object `PersonalChef`:
101 ```ruby
102 class PersonalChef
104 end
105 ```
107 Inside the class we usually define one or more methods using the `def` keyword like this:
109 ```ruby
110 class PersonalChef
111 def make_toast
112 puts "Making your toast!"
113 end
114 end
115 ```
117 Inside the `def` and `end` lines we'd put the instructions that the chef should perform when we say `make_toast`.
119 Once we define a class, we create an `instance` of that class like this:
121 ```ruby
122 frank =
123 ```
125 We're calling the `new` method on the class `PersonalChef` and storing it into the variable named `frank`. Once we have that instance, we can set or get its attributes and call its methods. Methods are called by using this syntax: `object.method_name`. So if you have a person named `frank` you would tell him to make toast by calling `frank.make_toast`.
127 ### Method Parameters
129 Sometimes methods take one or more _parameters_ that tell them _how_ to do what they're supposed to do. For instance, I might call `frank.make_toast('burned')` for him to burn my toast. Or maybe he has another method where I call `frank.make_breakfast("toast","eggs")` for him to make both toast and eggs. Parameters can be numbers, strings, or any kind of object. When a method takes a parameter it'll look like this:
131 ```ruby
132 class PersonalChef
133 def make_toast(color)
134 puts "Making your toast #{color}"
135 end
136 end
137 ```
139 Where the method is expecting us to pass in a `color` telling it how to do the method `make_toast`.
141 ### Return Value
143 In Ruby, every time you call a method you get a value back. By default, a Ruby method returns the value of the last expression it evaluated. If you called the `make_toast` method above, you should have seen the return value `nil`. The `puts` instruction always returns `nil`, so since that was the last instruction in your method you saw `nil` when calling that method.
145 For the purposes of our next section I'm going to explicitly return the chef instance itself from the method. Imagine you are looking at your chef `frank`. You say "Frank, go make my toast", he tells you he's making the toast, then comes back to you to receive more instructions. He's "returning" himself to you. Here's how we implement it in code:
147 ```ruby
148 class PersonalChef
149 def make_toast(color)
150 puts "Making your toast #{color}"
151 return self
152 end
153 end
154 ```
156 ### Running Ruby from a File
158 It's getting annoying to rewrite the `PersonalChef` class in IRB every time we want to make a change, right? Let's put it into a text file and run the Ruby code from there.
160 * Exit your IRB session
161 * Note which folder your terminal is currently in, this is your "working directory"
162 * Using a plain-text editor like Notepad, Textmate, or RubyMine, create a file named `personal_chef.rb` with the contents from the previous section
163 * Reopen `irb` from your terminal
164 * Tell Ruby to load the file with the command `require 'personal_chef'`
165 * Recreate `frank` with the line `frank =`
166 * Call the `make_toast` method by entering `frank.make_toast("light_brown")`
168 That should work just like it did before when we ran it in IRB. Now let's make a change to the file by adding in this new method:
170 ```ruby
171 def make_eggs(quantity)
172 puts "Making you #{quantity} eggs!"
173 return self
174 end
175 ```
177 Save the file in your editor. Then we need to tell Ruby to re-read the file. We can do that with this instruction in IRB:
179 ```ruby
180 load 'personal_chef.rb'
181 ```
183 Now try calling `frank.make_eggs(6)` and it should work.
185 ### Method Chaining
187 Often we'll want to call multiple methods on an object one after the other -- this is called _method chaining_ . Still thinking about `frank`, we might want to call `make_toast` and `make_eggs` one after the other. We can call multiple methods by using the format `object.method1.method2.method3`. So for this example, we might say:
189 ```ruby
190 frank.make_toast("burned").make_eggs(6)
191 ```
193 To read that in Engish, we're telling `frank` to `make_toast` with the parameter `burned`, then _after that is completed_ telling him to `make_eggs` with the parameter `6`. Try it in your IRB and make sure it works!
195 ## 4. Strings
197 In Ruby a string is defined as a quote (`"`) followed by zero or more letters, numbers, or symbols and followed by another quote (`"`). Some simple strings would be `"hello"` or `"This sentence is a string!"`. Strings can be anything from `""`, the empty string, to really long sets of text. This whole tutorial, for instance, is stored in a string. Strings have a few important methods that we'll use.
199 * `length`<br/>Call `length` on a string to get back the number of characters in the string. For instance `"hello".length` would give you back `5`.
200 * `delete`<br/>Delete lets you specify a set of characters that should be removed from the original string. For instance, `"hello".delete("l")` would give you back `"heo"` after deleting all occurrences of `"l"`, or `"Good Morning!".delete("on")` would give you `"Gd Mrig"`
201 * `gsub`<br/>Call `gsub` to replace a substring with a different string. For instance, `"hello".gsub("ll","y yo")` would give you back `"hey yoo"`.
202 * `split`<br/>The `split` method is somewhat complex because it's used to break a single string into a set of strings. For instance, I could call `"Welcome to Ruby".split(" ")` and it would find the two occurrences of `" "` (a blank space) and split the string at those points, giving you back a set like this: `["Welcome","to","Ruby"]`
204 Experiment with the following samples in IRB:
206 ```ruby
207 tester = "Hello Everyone!"
208 tester.length
bab5a66 @jcasimir Updating HTML
jcasimir authored
209 tester.delete("l")
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
210 tester.gsub("Everyone!","Friends!")
211 t2 = "sample,data,from,a,CSV"
212 t2.split(",")
213 ```
215 Often with strings we want to pull out just a part of the whole -- this is called a substring. Try out these examples in `irb` assuming you already have `tester` from the last examples:
217 ```ruby
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
218 tester[0..4]
219 tester[6..14]
220 tester[6..-1]
221 tester[6..-2]
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
222 ```
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
224 The numbers inside the `[]` brackets specify which of the characters you want pulled out. They're numbered starting with zero. So the first example pulls out the letters from zero, the beginning of the string, up to and including position four. The second example pulls from `6` up to `14`. The last one goes from `6` up to...`-1`? If you specify a negative value, that is like counting back from the end. Using `-1` means the end of the string, so `6..-1` means "from `6` to the end of the string."
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
226 ### Combining Strings and Variables
228 It is extremely common that we want to combine the value of a variable with other strings. For instance, lets start with this simple example string:
230 ```ruby
231 "Happy Saturday!"
232 ```
234 When we put that into IRB it just spits back the same string. If we were writing a proper program we might want it to greet the user when they start the program by saying `"Happy"` then the day of the week. So we can't just put a string like `"Happy Saturday!"` or it'd be saying Saturday even on Tuesday.
236 What we need to do is combine a variable with the string. There are two ways to do that. The first and easiest approach is called _string concatenation_ which is basically just adding strings together like this:
238 ```ruby
239 today = "Saturday"
240 puts "Happy " + today + "!"
241 ```
243 In the first line we setup a variable to hold the day of the week, then in the second line we print the string `Happy` combined with the value of the variable `today` and the string `!`. You might be thinking "What was the point of that since we still just wrote Saturday in the first line?" Ok, well, if you were writing a real program you'd use Ruby's built-in date functions like this:
245 ```ruby
246 require 'date'
247 today ="%A")
248 puts "Happy " + today + "!"
249 ```
251 String concatenation works fine most of the time, but there is a gotcha that pops up. Try this:
253 ```ruby
254 today ="%A")
255 day_of_year =
256 puts "Happy " + today + "! It is the " + day_of_year + " day of the year."
257 ```
259 You should get an error complaining that Ruby "can't convert Fixnum into String". What does that mean? When Ruby is assembling the parts of that string it sees a string `"Happy "`, then a string in the variable `today`, then a string with the ! and a few words, then a the variable `day_of_year`, then the string `"day of the year."`.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
261 The problem is that ruby knows how to add one string to another, but it's not sure how to add a string to a number. `day_of_year` contains a number, and when it tries to combine the strings with that number Ruby isn't sure what to do. Thankfully numbers have a method which converts them into a string so they can be combined with strings. That method is `.to_s` for "to string". Retry your example with this slight change:
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
263 ```ruby
264 today ="%A")
265 day_of_year =
266 puts "Happy " + today + "! It is the " + day_of_year.to_s + " day of the year."
267 ```
269 Great, no errors and our output looks correct. Having to remember that `.to_s` whenever you use a number a pain, though. There is another combination method that forces the "to string" conversion for you called _string interpolation_.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
271 ### String Interpolation
273 *String interpolation* is the process of sticking data into the middle of strings. We use the interpolation marker `#{}`. Inside those brackets we can put any variables or Ruby code which will be evaluated, converted to a string, and output in that spot. Our previous example could be rewritten like this:
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
275 ```ruby
276 puts "Happy #{today}! It is the #{day_of_year} day of the year."
277 ```
279 If you compare the output you'll see that this second method gives the exact same results. The code itself is a little more compact and I find it much easier to read.
281 You can also put any Ruby code or calculations inside the brackets when interpolating like this example:
283 ```ruby
284 modifier = "very "
285 mood = "excited"
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
286 puts "I am #{modifier * 3 + mood} for today's class!"
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
287 ```
289 #### Back to Frank
291 Write a `good_morning` method on the `PersonalChef` object that, when called, prints out a message like "Happy Wednesday, it's the 132 day of 2011."
293 ## 5. Symbols
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
295 Symbols are difficult to explain. You can recognize a symbol because it starts with a colon then one or more letters like `:flag` or `:best_friend`.
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
297 Think of it as a stripped down string that has barely any methods and no string interpolation. Compare the method list for a proper string versus a similar symbol like this:
299 ```ruby
300 "hello".methods
301 "hello".methods.count
302 :hello.methods
303 :hello.methods.count
304 ```
306 Symbols are used for passing information around inside our program. We'd never print a symbol out to a user -- for that we'd use a string.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
308 When starting out with pure Ruby you might not use symbols very frequently. But when you graduate to Ruby on Rails, they are everywhere. If you see an object that looks like `:this`, you'll know it's a symbol.
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
310 ## 6. Numbers
312 There are two basic kinds of numbers: integers (whole numbers) and floats (have a decimal point). For most programs you can get away with just integers, and I recommend avoiding floats whenever possible. Integers are much easier for both you and the computer to work with.
314 You can use normal math operations with integers including `+`, `-`, `/`, and `*`. Integers have a bunch of methods to help you do math-related things, which you can see by calling `5.methods`.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
316 ### Iterating
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
318 A common function in *other* languages is the for loop, used to repeat an instruction a set number of times. An example:
320 ```
321 for(int i=0; i < 5; i++){
322 printf "Hello, World"
323 }
324 ```
326 But that's not very readable unless you're familiar with the construct. In Ruby, because our integers are proper objects, we have the handy `times` method to repeat an instruction a set number of times.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
328 ### Revisiting Making Eggs
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
330 Let's take another look at Frank's `make_eggs` method. We can rebuild it to take advantage of the `times` method like this:
332 ```ruby
333 def make_eggs(quantity)
334 quantity.times do
335 puts "Making an egg."
336 end
337 puts "I'm done!"
338 return self
339 end
340 ```
342 In this example we're using the `times` method with a `do`/`end` block. When we call the `times` method we need to tell it what to *do* that number of times. Ruby looks for the starting keyword `do` and the ending keyword `end`. Each instruction between the `do` and `end` will be executed this number of `times`. Try this example with multiple instructions:
344 Try reloading the file with `load "personal_chef.rb"` and executing the `make_eggs` method for `frank`.
346 ## 7. Collections
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
348 Usually when we're writing a program it's because we need to deal with a *collection* of data. There are two main types of collections in Ruby: *arrays* and *hashes*.
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
350 ### Arrays
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
352 An *array* is a number-indexed list. Picture a city block of houses. Together they form an array and their addresses are the *indices*. Each house on the block will have a unique address. Some addresses might be empty, but the addresses are all in a specific order. The *index* is the address of a specific element inside the array. In Ruby the index always begins with `0`. An array is defined in Ruby as an opening [, then zero or more elements, then a closing ]. Try out this code:
354 ```ruby
355 meals = ["breakfast","lunch","dinner"]
356 puts meals[2]
357 puts meals.first
358 puts meals.last
359 ```
361 Keep going with these, but note that the first line below should give you some unusual output. Try and understand what Ruby is telling you:
363 ```ruby
364 puts meals[3]
365 meals << "dessert"
366 puts meals[3]
367 puts meals
368 ```
370 In order to get a specific element in the array you use the syntax `arrayname[index]`.
372 There are lots of cool things to do with an array. You can rearrange the order of the elements using the `sort` method. You can iterate through each element using the `each` method. You can mash them together into one string using the `join` method. You can find the address of a specific element by using the `index` method. You can ask an array if an element is present with the `include?` method. Try adding this method to `PersonalChef` that manipulates an array:
374 ```ruby
375 def gameplan
376 meals.each do |meal|
377 puts "We'll have #{meal}..."
378 end
380 all_meals = meals.join(", ")
381 puts "In summary: #{all_meals}"
382 end
383 ```
385 We use arrays whenever we need a list where the elements are in a specific order.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
387 ### Hashes
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
389 A hash is a collection of data where each element of data is addressed by a *name*. As an analogy, think about a refrigerator. If we're keeping track of the produce inside the fridge, we don't really care about what shelf it's on -- the order doesn't matter. Instead we organize things by *name*. Like the name "apples" might have the value 3, then the name "oranges" might have the value 1, and "carrots" the value 12. In this situation we'd use a hash.
391 A hash is an *unordered* collection where the data is organized into "key/value pairs". Hashes have a more complicated syntax that takes some getting used to:
393 ```ruby
394 produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
395 puts "There are #{produce['oranges']} oranges in the fridge."
396 ```
398 The *key* is used as the address and the *value* is the data at that address. In the `produce` hash we have keys including `"apples"` and `"oranges"` and values including `12` and `3`. When creating a hash the key and value are linked by the `=>` symbol which is called a _rocket_. So hashes start with a curly bracket `{`, have zero or more entries made up of a _key_, a rocket, and a _value_ separated by commas, then end with a closing curly bracket `}`. Try a few more steps:
400 ```ruby
401 produce["grapes"] = 221
402 produce
403 produce["oranges"] = 6
404 produce
405 produce.keys
406 produce.values
407 ```
409 In the first line of those instructions, we add a new value to the hash. Since the `"grapes"` key wasn't in the original hash, it's added with the value of `221`. Keys in the hash *must be unique*, so when we use the same syntax with `produce["oranges"]` it sees that the key `oranges` is already in the list and it replaces the value with `6`. The `keys` and `values` methods will also give you just half of the pairs.
411 #### Creating an Inventory
413 Let's write a method for `PersonalChef` that uses and manipulates a hash:
415 ```ruby
416 def inventory
417 produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
418 produce.each do |item, quantity|
419 puts "There are #{quantity} #{item} in the fridge."
420 end
421 end
422 ```
424 That walks through each of the pairs in the inventory, puts the key into the variable `item` and the value into the variable `quantity`, then prints them out.
426 ## 8. Conditionals
428 Conditional statements evaluate to `true` or `false`. The most common conditional operators are `==` (equal), `>` (greater than), `>=` (greater than or equal to), `<` (less than), and `<=` (less than or equal to).
430 Some objects also have methods which return a `true` or `false`, so they're used in conditional statements. For example every object has the method `.nil?` which is `true` only when the object is `nil`. Arrays have a method named `.include?` which returns true if the array includes the specified element. The convention in Ruby is that a method which returns `true` or `false` should have a name ending in a `?`.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
432 ### Conditional Branching / Instructions
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
434 Why do we have conditional statements? Most often it's to control conditional instructions, especially `if`/`elsif`/`else` structures. Let's write an example by adding a method to our `PersonalChef` class:
436 ```ruby
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
437 def water_status(minutes)
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
438 if minutes < 7
439 puts "The water is not boiling yet."
440 elsif minutes == 7
441 puts "It's just barely boiling"
442 elsif minutes == 8
443 puts "It's boiling!"
444 else
445 puts "Hot! Hot! Hot!"
446 end
447 return self
448 end
449 ```
451 Use `load` to re-read the file, then try this example using `5`, `7`, `8` and `9` for the values of `minutes`.
453 When the `minutes` is 5, here is how the execution goes: "Is it `true` that 5 is less than 7? Yes, it is, so print out the line `The water is not boiling yet.`".
455 When the `minutes` is 7, it goes like this: "Is it `true` that 7 is less than 7? No. Next, is it `true` that 7 is equal to 7? Yes, it is, so print out the line `It's just barely boiling`".
457 When the `minutes` is 8, it goes like this: "Is it `true` that 8 is less than 7? No. Next, is it `true` that 8 is equal to 7? No. Next, is it `true` that 8 is equal to 8? Yes, it is, so print out the line `It's boiling!`".
459 Lastly, when total is 9, it goes: "Is it `true` that 9 is less than 7? No. Next, is it `true` that 9 is equal to 7? No. Next, is it `true` that 9 is equal to 8? No. Since none of those are true, execute the `else` and print the line `Hot! Hot! Hot!`.
461 An `if` block has...
462 * One `if` statement whose instructions are executed only if the statement is true
463 * Zero or more `elsif` statements whose instructions are executed only if the statement is true
464 * Zero or one `else` statement whose instructions are executed if no `if` nor `elsif` statements were true
466 Only _one_ section of the `if`/`elsif`/`else` structure can have it's instructions run. If the `if` is `true`, for instance, Ruby will never look at the `elsif`. Once one block executes, that's it.
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
468 ### Conditional Looping
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
470 We can also repeat a set of instructions based on the truth of a conditional statement. Try out this example by adding it to your `personal_chef.rb`:
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
472 ```ruby
473 def countdown(counter)
474 while counter > 0
475 puts "The counter is #{counter}"
476 counter = counter - 1
477 end
478 return self
479 end
480 ```
482 See how that works? The `counter` starts out as whatever parameter we pass in. The `while` instruction evaluates the conditional statement `counter > 0` and finds that yes, the counter is greater than zero. Since the condition is `true`, execute the instructions inside the loop. First print out `"The counter is #{counter}"` then take the value of `counter`, subtract one from it, and store it back into `counter`. Then the loop goes back to the `while` statement. Is it still `true`? If so, print the line and subtract one again. Keep repeating until the condition is `false`.
484 I most often use `while`, but you can achieve the same results using `until` as well. Try this...
486 ```ruby
487 def countdown(counter)
488 until counter == 0
489 puts "The counter is #{counter}"
490 counter = counter - 1
491 end
492 return self
493 end
494 ```
4a6b95e @jcasimir Minor edits to Ruby in 100
jcasimir authored
496 ### Equality vs. Assignment
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
498 The #1 mistake people encounter when writing conditional statements is the difference between `=` and `==`.
dfff296 @jcasimir Fixing a few layout bugs
jcasimir authored
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
500 * `=` is an _assignment_. It means "take what's on the right side and stick it into whatever is on the left side" -- it's _telling_, not _asking_
dfff296 @jcasimir Fixing a few layout bugs
jcasimir authored
0225199 @jcasimir Adding Ruby Level 1 Tutorials
jcasimir authored
502 * `==` is a _question_. It means "is the thing on the right equal to the thing on the left?" -- it's _asking_, not _telling_
504 You can also combine conditional statements using logical operators. The most common are known as "logical and" and "logical or". In Ruby you can write a "logical and" with double ampersands like this: `&&`. You can write a logical or with double pipes like this: `||`.
506 ## 9. Nil & Nothingness
508 What is nothingness? Is there nothingness only in outer space? Really, when we think of "nothing" isn't it just the absence of something? Ok, that's too much philosophy...
510 `nil` is Ruby's way of referring to "nothingness."
512 If you have three eggs, eat three eggs, then you might think you have "nothing", but in terms of eggs you have "0". Zero is something, it's a number, and it's not nothing.
514 If you're working with words and have a string like "hello" then delete the "h", "e", "l"s, and "o" you might think you'd end up with nothing, but you really have "" which is an empty string. It's still something.
516 `nil` is Ruby's idea of nothingness. It's usually encountered when you ask for something that doesn't exist. When looking at arrays, for instance, we created a list with five elements then asked Ruby to give us the sixth element of that list. There is no sixth element, so Ruby gave us `nil`. It isn't that there's a blank in that sixth spot (`""`), it's not a number `0`, it's nothingness -- `nil`.
518 A large percentage of the errors you encounter while writing Ruby code will involve `nil`. You thought something was there, you tried to do something to it, and you can't do something to nothing so Ruby creates an error. Let's rewrite our `make_toast` method to illustrate `nil`:
520 ```ruby
521 def make_toast(color)
522 if color.nil?
523 puts "How am I supposed to make nothingness toast?"
524 else
525 puts "Making your toast #{color}!"
526 end
527 return self
528 end
529 ```
531 Reload the file, call `frank.make_toast("light brown")` then try `frank.make_toast(nil)`. The only method we can rely on `nil` executing is `.nil?`, pretty much anything else will create an error.
533 #### You've Got the Vocabulary
535 Alright, that's a quick introduction to the language. Now you're ready to dive into your Ruby!
Something went wrong with that request. Please try again.