Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 780 lines (505 sloc) 33.533 kb
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
1 ---
2 layout: page
3 title: Ruby in 100 Minutes
b7d0816 Franklin Webber Adding sidebar to ruby 100 minutes tutorial
burtlo authored
4 sidebar: true
bc3ec57 Franklin Webber Adding exercise tag to various tutorials
burtlo authored
5 pdf: false
440d141 Franklin Webber Alias Generator
burtlo authored
6 alias: [ /ruby_in_100_minutes, /ruby ]
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
7 ---
8
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
9 In this tutorial we'll explore the fundamental syntax you need to get started programming with Ruby.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
10
ca462a3 Jeff Casimir Updating HTML
jcasimir authored
11 <div class="note">
800355b Steve Klabnik setup -> set up
steveklabnik authored
12 <p>If you haven't already set up Ruby, visit <a href="/topics/environment/environment.html">the environment setup page for instructions</a>.</p>
ca462a3 Jeff Casimir Updating HTML
jcasimir authored
13 </div>
14
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
15 ## Ruby History
16
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
17 Ruby is thought of by many as a "new" programming language, but it was actually released back 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.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
18
44464d4 Jane Dallaway Update ruby_in_100_minutes.markdown
janedallaway authored
19 Ruby 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 had to learn Japanese first. 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"](http://pragprog.com/book/ruby/programming-ruby), due to its cover image, which opened Ruby to the English-speaking world.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
20
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
21 From there Ruby started growing in the English-speaking world, 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.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
22
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
23 In 2004-2005 a Chicago company named 37Signals hired a young developer 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 Perl CGI, PHP, Java's JSP, and Microsoft's ASP. They were each somewhat painful, so David, today known as DHH, went his own direction.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
24
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
25 He wrote the application in Ruby. He relied on the core library 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.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
26
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
27 Then, once Basecamp was built, DHH extracted the web framework out of it. This was a very different approach from Java/Sun or .NET/Microsoft where the web frameworks were handed down from on high. Instead, Rails was extracted from the real world. It focused on convention over configuration and making the common problems easy to solve.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
28
7f43c65 Jeff Casimir Revise the Ruby History Intro
jcasimir authored
29 That approach was a big hit and Rails has powered the growth of the Ruby community ever since. Now we have dozens of books on Amazon, nearly a hundred conferences around the world, and thousands of people employed as Ruby/Rails developers.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
30
31 And if you want to learn Rails, you need to learn Ruby first! Here goes...
32
33 ## 1. Instructions & Interpreters
34
b567d1c Jane Dallaway Update ruby_in_100_minutes.markdown
janedallaway authored
35 Ruby is an "interpreted" programming language which means it can't run on your processor directly, it has to be fed into a middleman called the "virtual machine" or VM. The VM takes in Ruby code on one side and speaks natively to the operating system and processor on the other. The benefit to this approach is that you can write Ruby code once and, typically, execute it on many different operating systems and hardware platforms.
dee4d35 Jeff Casimir Revised Instructions & Interpreters
jcasimir authored
36
37 A Ruby program can't run on it's own, you need to load the VM. There are two ways to execute Ruby with the VM: through IRB and through the command line.
38
39 ### Running Ruby from the Command Line
40
41 This is the durable way to write Ruby code because you save your instructions into a file. That file can then be backed up, transferred, added to source control, etc.
42
43
44 #### An Example Ruby File
45
46 We might create a file named `my_program.rb` like this:
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
47
48 ```ruby
99228b2 Jeff Casimir Removing excess whitespace from Ruby in 100
jcasimir authored
49 class Sample
50 def hello
51 puts "Hello, World!"
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
52 end
99228b2 Jeff Casimir Removing excess whitespace from Ruby in 100
jcasimir authored
53 end
88aefea Franklin Webber Exercises with the Examples
burtlo authored
54
99228b2 Jeff Casimir Removing excess whitespace from Ruby in 100
jcasimir authored
55 s = Sample.new
56 s.hello
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
57 ```
58
59 Then we could run the program like this:
60
59fa1ad Franklin Webber Updated 100 minutes tutorial to use irb/terminal tag
burtlo authored
61 {% terminal %}
62 $ ruby my_program.rb
63 Hello, World!
64 {% endterminal %}
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
65
dee4d35 Jeff Casimir Revised Instructions & Interpreters
jcasimir authored
66 When you run `ruby my_program.rb` you're actually loading the `ruby` virtual machine which in turn loads your `my_program.rb`.
67
68 ### Running Ruby from IRB
69
70 Ruby was one of the first languages to popularize what's called a "REPL": Read, Evaluate, Print, Loop. Think of it kind of like a calculator -- as you put in each complete instruction, IRB executes that instruction and shows you the result.
71
72 IRB is best used as a scratch pad for experimenting. Many developers keep an IRB window open while writing their "real" programs, using it to remember how a certain method works or debug a chunk of code.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
73
dee4d35 Jeff Casimir Revised Instructions & Interpreters
jcasimir authored
74 Let's begin our experiments with IRB. **Start IRB by opening Terminal (Mac) or Command Prompt (Win) and typing `irb`**.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
75
76 ## 2. Variables
77
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
78 Programming is all about creating abstractions, and in order to create an abstraction we must be able to assign names to things. Variables are a way of creating a name for a piece of data.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
79
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
80 In some languages you need to specify what type of data (like a number, word, etc) can go in a certain variable. Ruby, however, has a flexible type system where any variable can hold any kind of data.
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
81
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
82 ### Creating & Assigning a Variable
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
83
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
84 In some languages you need to "declare" a variable before you assign a value to it. Ruby variables are automatically created when you assign a value to them. Let's try an example:
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
85
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
86 {% irb %}
87 $ a = 5
88 => 5
89 $ a
90 => 5
91 {% endirb %}
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
92
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
93 The line `a = 5` creates the variable named `a` and stores the value `5` into it.
bc3ec57 Franklin Webber Adding exercise tag to various tutorials
burtlo authored
94
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
95 #### Right Side First
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
96
da56ab5 Daniel San Update ruby_in_100_minutes.markdown
dan-mi-sun authored
97 In English we read left-to-right, so it's natural to read code left to right. But when evaluating an assignment using the single equals (`=`), Ruby actually evaluates the *right side first*. Take the following example:
88aefea Franklin Webber Exercises with the Examples
burtlo authored
98
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
99 {% irb %}
100 $ b = 10 + 5
101 => 15
102 $ b
103 => 15
104 {% endirb %}
bc3ec57 Franklin Webber Adding exercise tag to various tutorials
burtlo authored
105
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
106 The `10 + 5` is evaluated first, and the result is given the name `b`.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
107
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
108 #### Flexible Typing
88aefea Franklin Webber Exercises with the Examples
burtlo authored
109
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
110 Ruby's variables can hold any kind of data and can even change the type of data they hold. For instance:
88aefea Franklin Webber Exercises with the Examples
burtlo authored
111
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
112 {% irb %}
113 $ c = 20
114 => 20
115 $ c = "hello"
116 => "hello"
117 {% endirb %}
88aefea Franklin Webber Exercises with the Examples
burtlo authored
118
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
119 The first assignment gave the name `c` to the number `20`. The second assignment changed `c` to the value `"hello"`.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
120
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
121 #### Naming Variables
88aefea Franklin Webber Exercises with the Examples
burtlo authored
122
ffbaabe Luke Aiken Update ruby_in_100_minutes.markdown
lukeaiken authored
123 Most Ruby variables (local variables) have a few requirements imposed by the VM. They...
bc3ec57 Franklin Webber Adding exercise tag to various tutorials
burtlo authored
124
ffbaabe Luke Aiken Update ruby_in_100_minutes.markdown
lukeaiken authored
125 * always start with a lowercase letter (underscore is permitted, though uncommon)
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
126 * have no spaces
127 * do not contain most special characters like `$`, `@`, and `&`
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
128
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
129 In addition to those VM requirements, Rubyists have a few common style preferences for variable names:
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
130
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
131 * use *snake case* where each word in the name is lowercase and connected by underscores (`_`)
132 * are named after the meaning of their contents, not the type of their contents
85c4ea3 Jane Dallaway Minor spelling corrections
janedallaway authored
133 * aren't abbreviated
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
134
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
135 Good variable names might be `count`, `students_in_class`, or `first_lesson`.
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
136
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
137 A few examples of **bad** Ruby variable names include:
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
138
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
139 * `studentsInClass` -- uses *camel-case* rather than *snake-case*, should be `students_in_class`
140 * `1st_lesson` -- variables can't start with a number, should just be `first_lesson`
141 * `students_array` -- includes the type of the data in the name, should just be `students`
142 * `sts` -- abbreviates rather than just using `students`
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
143
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
144 ### Exercises
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
145
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
146 Use IRB to store values with each of the following variable names. Which names are good, which are actually invalid Ruby, and which are valid but go against Ruby style?
88aefea Franklin Webber Exercises with the Examples
burtlo authored
147
57aaad2 Jeff Casimir Revising variables section
jcasimir authored
148 * `time_machine`
149 * `student_count_integer`
150 * `homeworkAssignment`
151 * `3_sections`
152 * `top_ppl`
bc3ec57 Franklin Webber Adding exercise tag to various tutorials
burtlo authored
153
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
154 ## 3. Strings
155
df53cea Jeff Casimir Revising Strings section
jcasimir authored
156 In the real world strings tie things up. Programming strings have *nothing* to do with real-world strings.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
157
df53cea Jeff Casimir Revising Strings section
jcasimir authored
158 Programming strings are used to store collections of letters and numbers. That could be a single letter like `"a"`, a word like `"hi"`, or a sentence like `"Hello my friends."`.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
159
df53cea Jeff Casimir Revising Strings section
jcasimir authored
160 ### Writing a String
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
161
df53cea Jeff Casimir Revising Strings section
jcasimir authored
162 A Ruby string is defined as a quote (`"`) followed by zero or more letters, numbers, or symbols and followed by a closing quote (`"`). The shortest possible string is called the empty string: `""`. It's not uncommon for a single string to contain paragraphs or even pages of text.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
163
df53cea Jeff Casimir Revising Strings section
jcasimir authored
164 ### Substrings
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
165
df53cea Jeff Casimir Revising Strings section
jcasimir authored
166 Often with strings we want to pull out just a part of the whole -- this is called a substring. Try these examples in `irb`:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
167
168 {% irb %}
169 $ greeting = "Hello Everyone!"
df53cea Jeff Casimir Revising Strings section
jcasimir authored
170 $ greeting[0..4]
171 $ greeting[6..14]
172 $ greeting[6..-1]
173 $ greeting[6..-2]
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
174 {% endirb %}
175
df53cea Jeff Casimir Revising Strings section
jcasimir authored
176 #### Positive and Negative Positions
177
178 The characters in a string each have a position number, starting with zero. So for a string `"Hi"`, the `"H"` is in position zero and the `"i"` is in position 1.
179
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
180 To pull out a substring we use the starting and ending positions. Thus `greeting[0..4]` above pull out the letters in position zero, one, two, three, and four.
df53cea Jeff Casimir Revising Strings section
jcasimir authored
181
182 Ruby interprets negative positions to count back from the end of the string. So in `"Hi"`, the `"i"` is in position -1 and the `"H"` is in position -2.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
183
85c4ea3 Jane Dallaway Minor spelling corrections
janedallaway authored
184 So if a letter has both a positive and negative position number, which should you use? If you can use the positive numbers do it, they're easier to reason about. But, if you're looking for something based on it being at the end of the string (like "What's the last character of this string?"), then use the negative positions.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
185
df53cea Jeff Casimir Revising Strings section
jcasimir authored
186 ### Common String Methods
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
187
df53cea Jeff Casimir Revising Strings section
jcasimir authored
188 Let's experiment with strings and some common methods in IRB.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
189
df53cea Jeff Casimir Revising Strings section
jcasimir authored
190 #### `.length`
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
191
df53cea Jeff Casimir Revising Strings section
jcasimir authored
192 The length method tells you how many characters (including spaces) are in the string:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
193
194 {% irb %}
195 $ greeting = "Hello Everyone!"
df53cea Jeff Casimir Revising Strings section
jcasimir authored
196 => "Hello Everyone!"
197 $ greeting.length
198 => 15
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
199 {% endirb %}
200
df53cea Jeff Casimir Revising Strings section
jcasimir authored
201 **Try It:** Calculate the total length of your name
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
202
df53cea Jeff Casimir Revising Strings section
jcasimir authored
203 #### `.split`
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
204
df53cea Jeff Casimir Revising Strings section
jcasimir authored
205 Often you'll have string that you want to break into parts. For instance, imagine you have a sentence stored in a string and want to break it into words:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
206
df53cea Jeff Casimir Revising Strings section
jcasimir authored
207 {% irb %}
208 $ sentence = "This is my sample sentence."
209 => "This is my sample sentence."
210 $ sentence.split
211 => ["This", "is", "my", "sample", "sentence."]
212 {% endirb %}
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
213
df53cea Jeff Casimir Revising Strings section
jcasimir authored
214 The `.split` method gives you back an Array which we'll learn about in a later section. It cuts the string wherever it encounters a space (`" "`) character.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
215
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
216 ##### `.split` with an Argument
df53cea Jeff Casimir Revising Strings section
jcasimir authored
217
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
218 But sometimes you'll want to split on a character other than space. The `.split` method takes an argument, a piece of data that tells it how to do what it does.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
219
220 {% irb %}
df53cea Jeff Casimir Revising Strings section
jcasimir authored
221 $ numbers = "one,two,three,four,five"
222 => "one,two,three,four,five"
223 $ numbers.split
224 => ["one,two,three,four,five"]
225 $ numbers.split(",")
226 => ["one", "two", "three", "four", "five"]
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
227 {% endirb %}
228
df53cea Jeff Casimir Revising Strings section
jcasimir authored
229 In the first call to `split` it tries to cut on spaces but there are none, so you get back an Array of the entire string. In the second try, though, we specify that the splitting should happen wherever there is a comma, so we get back an Array of the five individual words.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
230
df53cea Jeff Casimir Revising Strings section
jcasimir authored
231 #### `.sub` and `.gsub`
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
232
df53cea Jeff Casimir Revising Strings section
jcasimir authored
233 These two methods can be used to replace parts of a string. They're like using "Find & Replace" in a word processor. `.sub`, short for substitute, replaces just a single occurance. `.gsub`, short for global substitute, replaces all occurances (like "Replace All").
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
234
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
235 For both `.sub` and `.gsub` you'll need to specify two arguments: first the substring you're wanting to replace and second the string you want to replace it with.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
236
237 {% irb %}
238 $ greeting = "Hello Everyone!"
df53cea Jeff Casimir Revising Strings section
jcasimir authored
239 $ greeting.gsub("Everyone!","Friends!")
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
240 {% endirb %}
241
242 ### Combining Strings and Variables
243
df53cea Jeff Casimir Revising Strings section
jcasimir authored
244 It is extremely common that we want to combine the value of a variable with a string. For instance, let's start with this example string:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
245
246 ```ruby
da56ab5 Daniel San Update ruby_in_100_minutes.markdown
dan-mi-sun authored
247 "Good morning, Frank!"
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
248 ```
249
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
250 When we put that into IRB it just spits back the same string. If we were writing a proper program, we'd want it to greet the user with their name rather than `"Frank"`.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
251
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
252 What we need to do is combine a variable with the string. There are two ways to do that.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
253
df53cea Jeff Casimir Revising Strings section
jcasimir authored
254 #### String Concatenation
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
255
df53cea Jeff Casimir Revising Strings section
jcasimir authored
256 The simplistic approach is called **string concatenation** which is joins strings together with the plus sign:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
257
258 {% irb %}
df53cea Jeff Casimir Revising Strings section
jcasimir authored
259 $ name = "Frank"
260 $ puts "Good morning, " + name + "!"
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
261 {% endirb %}
262
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
263 In the first line we set up a variable to hold the name. In the second line we print the string `"Good morning, ` combined with the value of the variable `name` and the string `"!"`.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
264
55c0019 Jeff Casimir Correct String header levels
jcasimir authored
265 #### String Interpolation
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
266
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
267 The second approach is to use *string interpolation* where we stick data into the middle of a string.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
268
df53cea Jeff Casimir Revising Strings section
jcasimir authored
269 String interpolation only works on a double-quoted string. Within the string 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 of the outer string. Our previous example could be rewritten like this:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
270
271 {% irb %}
df53cea Jeff Casimir Revising Strings section
jcasimir authored
272 $ name = "Frank"
273 $ puts "Good morning, #{name}!"
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
274 {% endirb %}
275
df53cea Jeff Casimir Revising Strings section
jcasimir authored
276 If you compare the output you'll see that they give the exact same results. The interpolation style tends to be fewer characters to type and fewer open/close quotes and plus signs to forget.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
277
55c0019 Jeff Casimir Correct String header levels
jcasimir authored
278 ##### Executing Code Inside Interpolation
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
279
df53cea Jeff Casimir Revising Strings section
jcasimir authored
280 You can also put any Ruby code or calculations inside the brackets when interpolating like this:
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
281
282 {% irb %}
283 $ modifier = "very "
284 $ mood = "excited"
285 $ puts "I am #{modifier * 3 + mood} for today's class!"
286 {% endirb %}
287
df53cea Jeff Casimir Revising Strings section
jcasimir authored
288 The snippet `modifier * 3 + mood` is evaluated first, then the result is injected into the outer string.
f32873d Jeff Casimir Let's do Strings before Objects
jcasimir authored
289
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
290 ## 4. Symbols
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
291
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
292 Symbols are difficult to explain, they're halfway between a string and a number. You can recognize a symbol because it starts with a colon then one or more letters, like `:flag` or `:best_friend`.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
293
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
294 ### Symbols for New Programmers
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
295
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
296 If you're new to programming, think of a symbol 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:
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
297
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
298 {% irb %}
299 $ "hello".methods
300 $ "hello".methods.count
301 $ :hello.methods
302 $ :hello.methods.count
303 {% endirb %}
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
304
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
305 ### Symbols for Experienced Programmers
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
306
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
307 If you're an experienced programmer, think of a symbol as a "named integer". It doesn't matter what actual value the symbol references. All we care about is that any reference to that value within the VM will give back the same value. Symbols are thus defined in a global symbol table and their value cannot change.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
308
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
309 ## 5. Numbers
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
310
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
311 There are two basic kinds of numbers: integers (whole numbers) and floats (have a decimal point).
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
312
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
313 Integers are much easier for both you and the computer to work with. 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`.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
314
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
315 ### Repeating Instructions
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
316
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
317 A common pattern in *other* languages is the `for` loop, used to repeat an instruction a set number of times. For example, in JavaScript you might write:
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
318
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
319 ```javascript
320 for(var i = 0; i < 5; i++){
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
321 console.log("Hello, World");
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
322 }
323 ```
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
324
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
325 For loops are common, but they're not very readable. Because Ruby's integers are objects they have methods. One of those is the `times` method to repeat an instruction a set number of times.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
326
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
327 To rewrite the above loop in a Ruby style:
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
328
01bea6d Jeff Casimir Revising Symbols to come before numbers
jcasimir authored
329 ```ruby
330 5.times do
331 puts "Hello, World!"
332 end
333 ```
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
334
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
335 In this example we're using both the `times` method and what's called a *block*. We'll discuss blocks in the next section. But go ahead and run this example in IRB to see what happens.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
336
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
337 ## 6. Blocks
338
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
339 Blocks are a powerful concept used frequently in Ruby. Think of them as a way of bundling up a set of instructions for use elsewhere.
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
340
341 ### Starting & Ending Blocks
342
343 You just saw a block used with the `.times` method on an integer:
344
345 ```ruby
346 5.times do
347 puts "Hello, World!"
348 end
349 ```
350
351 The block starts with the keyword `do` and ends with the keyword `end`. The `do`/`end` style is always acceptable.
352
353 #### Bracket Blocks
354
355 When a block contains just a single instruction, though, we'll often use the alternate markers `{` and `}` to begin and end the block:
356
357 ```ruby
358 5.times{ puts "Hello, World!" }
359 ```
360
361 ### Blocks Are Passed to Methods
362
363 So what is a block actually used for? They're a parameter passed into a method call.
364
365 If, for instance, we just called `5.times`, Ruby wouldn't know what we want to be done five times. When we pass in the block we're saying "here are the instructions I want you to run each time".
366
367 There are *many* methods that accept blocks. Like the `.gsub` method you saw on String earlier will run a block once for each match:
368
369 {% irb %}
370 $ "this is a sentence".gsub("e"){ puts "Found an E!"}
371 Found an E!
372 Found an E!
373 Found an E!
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
374 => "this is a sntnc"
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
375 {% endirb %}
376
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
377 Notice that the `Found an E!` line shows up three times because there were three Es in the string.
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
378
379 Why does the result say `"sntnc"`? That's a puzzle for you.
380
381 ### Block Parameters
382
85c4ea3 Jane Dallaway Minor spelling corrections
janedallaway authored
383 Often our instructions within a block need to reference the value that they're currently working with. When we write the block we can specify a block parameter inside pipe characters:
a74b590 Jeff Casimir First draft of a section about blocks
jcasimir authored
384
385 ```ruby
386 5.times do |i|
387 puts "Hello, World!"
388 end
389 ```
390
391 What value gets put into that block parameter is up to the method we're calling. In this case, the `times` method puts in the number of the current run. Try the block as it is above, observe the output, then try this:
392
393 ```ruby
394 5.times do |i|
395 puts "#{i}: Hello, World!"
396 end
397 ```
398
399 While `.gsub` passes in the string that it found. Try this (with the bracket notation):
400
401 ```ruby
402 $ "this is a sentence".gsub("e"){|letter| letter.upcase}
403 ```
404
405 You'll see that `gsub` is using the result of the block as the replacement for the original match.
e6cbab5 Jeff Casimir Reordering numbers and symbols
jcasimir authored
406
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
407 ## 7. Arrays
408
409 Usually when we're writing a program it's because we need to deal with a *collection* of data. Let's first look at the most common collection of data, the Array.
410
411 ### A Visual Model
412
413 An *array* is a number-indexed list. Imagine you had a blank piece of paper and drew a set of three small boxes in a line:
414
415 ```plain
416 --- --- ---
417 | || || |
418 --- --- ---
419 ```
420
421 You could number each one by its position left to right:
422
423 ```plain
424 --- --- ---
425 | || || |
426 --- --- ---
427 0 1 2
428 ```
429
430 Then put strings in each box:
431
432 ```plain
433 ------------- --------- ----------
434 | "Breakfast" || "Lunch" || "Dinner" |
435 ------------- --------- ----------
436 0 1 2
437 ```
438
439 We have a three element Array. Ruby arrays can grow and shrink, so if we added an element it'd usually go on the end:
440
441 ```plain
442 ------------- --------- ---------- -----------
443 | "Breakfast" || "Lunch" || "Dinner" || "Dessert" |
444 ------------- --------- ---------- -----------
445 0 1 2 3
446 ```
447
448 Note how the position of the last element is always one less than the number of elements.
449
450 If you asked the array for the element in position two you'd get back `"Dinner"`. Ask for the last element and you'd get back `"Dessert"`.
451
452 ### Arrays in Code
453
454 Here's how we would go through the same modeling in Ruby code:
455
456 {% irb %}
457 $ meals = ["Breakfast", "Lunch", "Dinner"]
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
458 => ["Breakfast", "Lunch", "Dinner"]
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
459 $ meals << "Dessert"
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
460 => ["Breakfast", "Lunch", "Dinner", "Dessert"]
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
461 $ meals[2]
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
462 => "Dinner"
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
463 $ meals.last
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
464 => "Dessert"
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
465 {% endirb %}
466
467 Observe that...
468
469 * the array was created by putting pieces of data between square brackets (`[]`) and separated by commas
470 * we add an element to the end of an array by using the "shovel operator" (`<<`)
471 * we fetch the element at a specific position by using square brackets (`[]`)
a38ed5b Logan Sears Update ruby_in_100_minutes.markdown
Diasporism authored
472 * there are convenience methods like `.last`
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
473
474 ### Common Array Methods
475
476 There are lots of cool things to do with an array. Here are a few examples:
477
60e541e Jeff Casimir Found one more PersonalChef reference
jcasimir authored
478 #### Explanation of `.sort`
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
479
480 The sort method will return a new array where the elements are sorted. If the elements are strings they'll come back in alphabetacal order. If they're numbers they'll come back in ascending value order. Try these:
481
482 {% irb %}
483 $ one = ["this", "is", "an", "array"]
484 $ one.sort
485 $ one
486 {% endirb %}
487
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
488 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.
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
489
490 We use arrays whenever we need a list where the elements are in a specific order.
491
60e541e Jeff Casimir Found one more PersonalChef reference
jcasimir authored
492 #### Others to Try
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
493
60e541e Jeff Casimir Found one more PersonalChef reference
jcasimir authored
494 Try experimenting with these common methods on Array:
495
496 * `each`
497 * `collect`
498 * `first` and `last`
499 * `shuffle`
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
500
60e541e Jeff Casimir Found one more PersonalChef reference
jcasimir authored
501 You can reference the documentation for more details here: http://www.ruby-doc.org/core-2.1.2/Array.html
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
502
503 ## 8. Hashes
504
505 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.
506
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
507 ### Key/Value Pairs
508
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
509 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:
510
511 {% irb %}
512 $ produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
513 $ puts "There are #{produce['oranges']} oranges in the fridge."
514 {% endirb %}
515
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
516 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 `}`.
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
517
518 Try a few more steps:
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
519
520 {% irb %}
521 $ produce["grapes"] = 221
522 $ produce
523 $ produce["oranges"] = 6
524 $ produce
525 $ produce.keys
526 $ produce.values
527 {% endirb %}
528
529 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.
530
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
531 ### Simplified Hash Syntax
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
532
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
533 We'll very commonly use symbols as the keys of a hash. When all the keys are symbols, then there is a shorthand syntax which can be used:
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
534
535 {% irb %}
536 $ produce = {apples: 3, oranges: 1, carrots: 12}
537 $ puts "There are #{produce[:oranges]} oranges in the fridge."
538 {% endirb %}
539
540 Notice that the keys end with a colon rather than beginning with one, even though these are symbols. This simplified syntax works with Ruby version 1.9 and higher. To find out which version of Ruby you have type "ruby -v" into the console.
541
542 ## 9. Conditionals
543
544 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).
545
546 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 `?`.
547
548 ### Conditional Branching / Instructions
549
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
550 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 like this in IRB:
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
551
552 ```ruby
553 def water_status(minutes)
554 if minutes < 7
555 puts "The water is not boiling yet."
556 elsif minutes == 7
557 puts "It's just barely boiling"
558 elsif minutes == 8
559 puts "It's boiling!"
560 else
561 puts "Hot! Hot! Hot!"
562 end
563 end
564 ```
565
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
566 Try running the method with `water_status(5)`, `water_status(7)`, `water_status(8)`, and `water_status(9)`.
567
568 #### Understanding the Execution Flow
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
569
570 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.`".
571
572 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`".
573
574 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!`".
575
576 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!`.
577
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
578 #### `if` Possible Constructions
579
580 An `if` statement has...
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
581
582 * One `if` statement whose instructions are executed only if the statement is true
583 * Zero or more `elsif` statements whose instructions are executed only if the statement is true
584 * Zero or one `else` statement whose instructions are executed if no `if` nor `elsif` statements were true
585
586 Only _one_ section of the `if`/`elsif`/`else` structure can have its instructions run. If the `if` is `true`, for instance, Ruby will never look at the `elsif`. Once one block executes, that's it.
587
588 ### Equality vs. Assignment
589
590 The #1 mistake people encounter when writing conditional statements is the difference between `=` and `==`.
591
592 * `=` 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_
593
594 * `==` is a _question_. It means "is the thing on the right equal to the thing on the left?" -- it's _asking_, not _telling_
595
596 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: `||`.
597
598 ## 10. Nil & Nothingness
599
600 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...
601
602 `nil` is Ruby's way of referring to "nothingness."
603
604 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.
605
606 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.
607
608 `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`.
609
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
610 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 raises an error.
4705708 Jeff Casimir Writing about Arrays
jcasimir authored
611
58150c7 Jeff Casimir Revised up to Objects, Attributes, and Methods
jcasimir authored
612 ## 11. Objects, Attributes, and Methods
728d517 Jeff Casimir Reordering to demote Ruby from a File
jcasimir authored
613
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
614 ### Ruby is Object-Oriented
728d517 Jeff Casimir Reordering to demote Ruby from a File
jcasimir authored
615
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
616 Ruby is an Object-Oriented programming language which means that all the things we interact with inside the VM are objects. Each piece of data is an object. Objects hold information, called _attributes_, and they can perform actions, called _methods_.
728d517 Jeff Casimir Reordering to demote Ruby from a File
jcasimir authored
617
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
618 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 types of objects have different attributes and methods. In the next sections we'll look at a few specific kinds of objects common in Ruby.
619
620 ### Classes and Instances
621
622 In Object-Oriented programming we define *classes*, which are abstract descriptions of a category or type of thing. It defines what attributes and methods all objects of that type have.
623
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
624 #### Defining a Class
625
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
626 For example, let's think about modeling a school. We'd likely create a class named `Student` that represents the abstract idea of a student. The `Student` class would define attributes like `first_name`, `last_name`, and `primary_phone_number`. It could define a method `introduction` that causes the student to introduce themself.
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
627
628 Try this in IRB:
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
629
630 ```ruby
631 class Student
632 attr_accessor :first_name, :last_name, :primary_phone_number
633
634 def introduction
635 puts "Hi, I'm #{first_name}!"
636 end
637 end
638 ```
639
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
640 You haven't yet seen the `attr_accesor` method which is used to define attributes for instances of a class.
641
642 #### Creating Instances
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
643
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
644 The class itself doesn't represent a student, it's the *idea* of what a student is like. To represent an actual student we create an *instance* of that class.
db5c9d6 Jeff Casimir WIP revising objects/attributes/methods
jcasimir authored
645
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
646 Imagine you're a student. You're not an abstract concept, you're an actual person. This actual person is an *instance* of `Student` - it is a realization of the abstract idea. It has actual data for the attributes `first_name`, `last_name`, and `primary_phone_number`.
728d517 Jeff Casimir Reordering to demote Ruby from a File
jcasimir authored
647
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
648 The *class* `Student`, on the other hand, has an abstract `first_name`, `last_name`, and `primary_phone_number` -- we can't determine them ahead of time.
728d517 Jeff Casimir Reordering to demote Ruby from a File
jcasimir authored
649
650 ### Running Ruby from a File
88aefea Franklin Webber Exercises with the Examples
burtlo authored
651
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
652 We rarely use IRB for defining classes. It's just a scratchpad, remember? Let's look at how to run Ruby from a file.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
653
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
654 * Exit your IRB session (enter `exit`)
88aefea Franklin Webber Exercises with the Examples
burtlo authored
655 * Note which folder your terminal is currently in, this is your "working directory"
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
656 * Using a plain-text editor to create a file named `student.rb`.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
657 * Save the file in your editor
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
658 * Run the file from your terminal:
88aefea Franklin Webber Exercises with the Examples
burtlo authored
659
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
660 {% terminal %}
661 $ ruby student.rb
662 {% endterminal %}
663
664 You should get no output since the file is blank.
665
666 #### Creating a Student Class
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
667
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
668 In your text editor, begin the structure of the class like this:
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
669
670 ```ruby
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
671 class Student
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
672
673 end
674 ```
675
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
676 Inside the class we usually define one or more methods using the `def` keyword:
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
677
678 ```ruby
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
679 class Student
680 def introduction
681 puts "Hi, I'm #{first_name}!"
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
682 end
683 end
684 ```
685
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
686 Notice that the `puts` line is counting on there being a method named `first_name` which returns the first name of the student. Let's add the three attributes we used earlier:
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
687
688 ```ruby
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
689 class Student
690 attr_accessor :first_name, :last_name, :primary_phone_number
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
691
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
692 def introduction
693 puts "Hi, I'm #{first_name}!"
694 end
695 end
696 ```
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
697
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
698 #### Run the File
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
699
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
700 Go back to your terminal and try running the file with `ruby student.rb`. You should again get no output.
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
701
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
702 Why? We defined a student class and said that a student has a method named `introduction` along with a few attributes -- but we didn't actually create instances of that `Student` class or call any methods.
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
703
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
704 #### Creating an Instance
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
705
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
706 Once we define a class, we would create an `instance` of that class like this:
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
707
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
708 ```ruby
709 frank = Student.new
710 ```
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
711
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
712 We're calling the `new` method on the class `Student` and storing it into the variable named `frank`. Once we have that instance, we can set or get its attributes and call its methods. '
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
713
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
714 Methods are called by using this syntax: `object.method_name`. So if you have a variable named `frank`, you would tell him to introduce himself by calling `frank.introduction`.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
715
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
716 #### Creating an Instance in the File
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
717
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
718 At the bottom of your `student.rb`, after the closing `end` for the `Student` class, add the following:
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
719
720 ```ruby
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
721 frank = Student.new
722 frank.first_name = "Frank"
723 frank.introduction
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
724 ```
725
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
726 Save it, return to your terminal, and try `ruby student.rb` again. It should now output `Hi, I'm Frank!`
88aefea Franklin Webber Exercises with the Examples
burtlo authored
727
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
728 ### Method Arguments
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
729
c17ad83 Rachel Warbelow change 'parameter' to 'argument'
rwarbelow authored
730 Sometimes methods take one or more _arguments_ that tell them _how_ to do what they're supposed to do. For instance, I might call `frank.introduction('Katrina')` for him to introduce himself to Katrina. Arguments can be numbers, strings, or any kind of object. Modify your method to take an argument:
88aefea Franklin Webber Exercises with the Examples
burtlo authored
731
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
732 ```ruby
733 class Student
734 attr_accessor :first_name, :last_name, :primary_phone_number
88aefea Franklin Webber Exercises with the Examples
burtlo authored
735
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
736 def introduction(target)
737 puts "Hi #{target}, I'm #{first_name}!"
738 end
739 end
1387eb0 Jeff Casimir Removing blockquotes
jcasimir authored
740
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
741 frank = Student.new
742 frank.first_name = "Frank"
743 frank.introduction('Katrina')
744 ```
88aefea Franklin Webber Exercises with the Examples
burtlo authored
745
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
746 Now run your file again and you should see `Hi Katrina, I'm Frank`.
88aefea Franklin Webber Exercises with the Examples
burtlo authored
747
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
748 ### Return Value
749
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
750 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.
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
751
752 #### Adding `favorite_number`
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
753
63ece10 Jorge Tellez Minor fix on Ruby in 100 minutes
novohispano authored
754 Let's add a method named `favorite_number` to our class.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
755
88aefea Franklin Webber Exercises with the Examples
burtlo authored
756
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
757 ```ruby
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
758 class Student
759 attr_accessor :first_name, :last_name, :primary_phone_number
88aefea Franklin Webber Exercises with the Examples
burtlo authored
760
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
761 def introduction(target)
762 puts "Hi #{target}, I'm #{first_name}!"
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
763 end
764
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
765 def favorite_number
766 7
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
767 end
88aefea Franklin Webber Exercises with the Examples
burtlo authored
768 end
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
769
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
770 frank = Student.new
771 frank.first_name = "Frank"
772 puts "Frank's favorite number is #{frank.favorite_number}."
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
773 ```
774
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
775 Run that from your terminal and you should see `Frank's favorite number is 7`. The last line of the file is calling the `favorite_number` method. The last (and only) line of that method is just the line `7`. That then becomes the return value of the method, which is sent back to whomever called the method. In our case, that `7` comes back and gets interpolated into the string.
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
776
4ff9729 Jeff Casimir Completed first revision pass to Ruby in 100
jcasimir authored
777 ## You've Got the Vocabulary
d0f4e19 Jeff Casimir Adding Ruby Level 1 Tutorials
jcasimir authored
778
47dcc5b Katrina Owen Refer to Sublime Text rather than RubyMine
kytrinyx authored
779 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.