• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/191

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

191 Cards in this Set

  • Front
  • Back

Exercise 1


Terminal


It is located in the Utilities folder within the Applications folder. When launched, it provides a line interface to control the underpinnings of the UNIX based operating system

Exercise 1

How to run ruby
ruby ex1.rb



You need to be in the same directory as the file you created. Make sure you use the cdcommand to go there first. For example, if you saved your file in lrthw/ex1.rb, then you would do cd lrthw/ before trying to run ruby ex1.rb. If you don't know what any of that means, then go through Appendix A.

Exercise 1

puts

puts prints out what you type on a new line.

Exercise 2

How do you write a comment in ruby?
# A comment, this is so you can read your program later.

Exercise 2

What is a octothorpe
It is the # character

Exercise 3

What are the math symbols in ruby
+ plus (addition)


- minus (subtraction)


/ slash (division)


* asterisk (multiplication)


% percent (modulus get the remainder of a division problem)


< less-than (comparison of two)


> greater-than (comparison of two)


<= less-than-equal (comparison of two or equal)


>= greater-than-equal (comparison of two or equal)

Exercise 3

floating point number
8.0

Exercise 3

Integer
9
Exercise 4

variable

a variable is nothing more than a name for something

Exercise 4

What is the difference between = (single-equal) and == (double-equal)?
The = (single-equal) assigns the value on the right to a variable on the left. The == (double-equal) tests if two things have the same value. You'll learn about this in Exercise 27.
Exercise 5

string

Every time you put " (double-quotes) around a piece of text you have been making a string. A string is how you make something that your program might give to a human. You print strings, save strings to files, send strings to web servers, and many other things.

Exercise 5

How do you embed a variable inside a string
You embed variables inside a string by using a special #{} sequence and then put the variable you want inside the {} characters. This tells Ruby, "Hey, this string needs to be formatted. Put these variables in there."
Exercise 6

strings

A string is usually a bit of text you want to display to someone, or "export" out of the program you are writing. Ruby knows you want something to be a string when you put either " (double-quotes) or '(single-quotes) around the text. You saw this many times with your use of puts when you put the text you want to go inside the string inside " after the puts to print the string.
Exercise 6

strings

Strings can contain any number of variables that are in your Ruby script. Remember that a variable is any line of code where you set a name = (equal) to a value. In the code for this exercise, types_of_people = 10 creates a variable named types_of_people and sets it = (equal) to 10. You can put that in any string with #{types_of_people}.
Exercise 7

Can I use single-quotes or double-quotes to make a string or do they do different things?

In Ruby the " (double-quote) tell Ruby to replace variables it finds with #{}, but the '(single-quote) tells Ruby to leave the string alone and ignore any variables inside it.
Exercise 8

format string

  but rather than using variables, use values by their names.

  
but rather than using variables, use values by their names.





Exercise 8

Should I use %{} or #{} for formatting?

You will almost always use #{} to format your strings, but there are times when you want to apply the same format to multiple values. That's when %{} comes in handy.
Exercise 9

Multiple line string

puts """There's something going on here.With the three double-quotes.We'll be able to type as much as we like.Even 4 lines if we want, or 5, or 6."""
Exercise 10

string that goes across multiple lines

In the first way, I put the characters \n (backslash n) between the names of the months. These two characters put a new line character into the string at that point.
Exercise 10



\ backslash

This \ (backslash) character encodes difficult-to-type characters into a string. There are various "escape sequences" available for different characters you might want to use.

Exercise 10

escape single quote \' escape double \"
An important escape sequence is to escape a single-quote ' or double-quote ". Imagine you have a string that uses double-quotes and you want to put a double-quote inside the string. If you write "I "understand" joe." then Ruby will get confused because it will think the " around "understand" actuallyends the string. You need a way to tell Ruby that the " inside the string isn't a real double-quote.
Exercise 10

triple-quotes

which is just """ and works like a string, but you also can put as many lines of text as you want until you type """ again.


Exercise 10

Escape Sequences

ESCAPEWHAT IT DOES.

\\ Backslash


\' Single-quote


\" Double-quote


\a ASCII bell (BEL)


\b ASCII backspace (BS)


\f ASCII formfeed (FF)


\n ASCII linefeed (LF)


\r ASCII Carriage Return (CR)


\t ASCII Horizontal Tab (TAB)


\uxxxx Character with 16-bit hex value xxxx (Unicode only)\vASCII vertical tab (VT)\oooCharacter with octal value ooo\xhhCharacter with hex value hh

Exercise 11

Most of what software does is the following:

Take some kind of input from a person.


Change it.


Print out something to show how it changed.

Exercise 11

gets.chomp

gets accepts a single line of data from the standard input - the keyboard in this case - and assigns the string typed by the user to city.



The standard input is a default stream supplied by many operating systems that relates to the standard way to accept input from the user.




In our case, the standard input is the keyboard.chomp is a string method and gets retrieves only strings from your keyboard.




You must have realised that gets returns a string and a '\n' character, while chomp removes this '\n'.




variable = gets.chomp



Exercise 12

How do I get a number from someone so I can do math?


That's a little advanced, but try gets.chomp.to_i which says, "Get a string from the user, chomp off the \n, and convert it to an integer."
Exercise 12

What does .to_f do?

It converts the number to a floating point. Or you can convert a number string into a floating point. Or you can convert an integer into a floating point number.
Exercise 13

ARGV

is the "argument variable," a very standard name in programming, that you will find used in many other languages. This variable holds the arguments you pass to your Ruby script when you run it.
Exercise 13

first, second, third = ARGV

Line 1 "unpacks" ARGV so that, rather than holding all the arguments, it gets assigned to four variables you can work with: first, second, and third. This may look strange, but "unpack" is probably the best word to describe what it does. It just says, "Take whatever is in ARGV, unpack it, and assign it to all of these variables on the left in order."



In the command line


ruby ex13.rb first 2nd 3rd




You can actually replace first, 2nd, and 3rd with any three things you want.

Exercise 13

What's the difference between ARGV and gets.chomp?

The different has to do with where the user is required to give input. If they give your script inputs on the command line, then you use ARGV. If you want them to input using the keyboard while the script is running, then use gets.chomp.
Exercise 13

Are the command line arguments strings?

Yes, they come in as strings, even if you typed numbers on the command line. Use .to_i to convert them just like with gets.chomp.to_i.


Exercise 14

In this exercise we'll usegets.chomp slightly differently by having it print a simple > prompt. This is similar to a game like Zork or Adventure.

user_name = ARGV.first

prompt = '> '


puts "Hi #{user_name}."puts "I'd like to ask you a few questions."




puts "Do you like me #{user_name}? ", promptlikes = $stdin.gets.chompputs "Where do you live #{user_name}? ", prompt


lives = $stdin.gets.chompputs "What kind of computer do you have? ", prompt


computer = $stdin.gets.chomp




puts """Alright, so you said #{likes} about liking me.You live in #{lives}. Not sure where that is.And you have a #{computer} computer. Nice."""



Exercise 14

Variable prompt
We make a variable prompt that is set to the prompt we want, and we give that to gets.chomp instead of typing it over and over. Now if we want to make the prompt something else, we just change it in this one spot and rerun the script.
Exercise 15

Hard coding

What we want to do is "open" that file in our script and print it out. However, we do not want to just "hard code" the name ex15_sample.txt into our script. "Hard coding" means putting some bit of information that should come from the user as a string directly in our source code. That's bad because we want it to load other files later. The solution is to use ARGV or gets.chomp to ask the user what file to open instead of "hard coding" the file's name.
Exercise 15

CODE

filename = ARGV.first



txt = open(filename)




puts "Here's your file #{filename}:"


print txt.read




print "Type the filename again: "


file_again = $stdin.gets.chomp


txt_again = open(file_again)




print txt_again.read

Exercise 15

Break Down



Lines 1-2 uses ARGV to get a filename. Next we have line 3 where we use a new command open. Right now, run ri open and read the instructions. Notice how like your own scripts and gets.chomp, it takes a parameter and returns a value you can set to your own variable.



Line 5 prints a little message, but on line 6 we have something very new and exciting. We call a function on txt named read. What you get back from open is a File, and it also has commands you can give it. You give a file a command by using the . (dot or period), the name of the command, and parameters. Just like with open and gets.chomp. The difference is that txt.read says, "Hey txt! Do your read command with no parameters!"




Exercise 15

txt = open(filename)

where we use a new command open. Right now, run ri open and read the instructions. Notice how like your own scripts and gets.chomp, it takes a parameter and returns a value you can set to your own variable.


Exercise 15

print txt.read

We call a function on txt named read. What you get back from open is a File, and it also has commands you can give it. You give a file a command by using the . (dot or period), the name of the command, and parameters. Just like with open and gets.chomp. The difference is that txt.read says, "Hey txt! Do your read command with no parameters!"
Exercise 15

Does txt = open(filename) return the contents of the file?

No, it doesn't. It actually makes something called a "file object." You can think of a file like an old tape drive that you saw on mainframe computers in the 1950s, or even like a DVD player from today. You can move around inside them, and then "read" them, but the DVD player is not the DVD the same way the file object is not the file's contents.
Exercise 15

Why is there no error when we open the file twice?

Ruby will not restrict you from opening a file more than once and sometimes this is necessary.

Exercise 16

Reading and Writing Files

close -- Closes the file. Like File->Save.. in your editor

.read -- Reads the contents of the file. You can assign the result to a variable


.readline -- Reads just one line of a text file.


truncate -- Empties the file. Watch out if you care about the file


.write('stuff') -- Writes "stuff" to the file.

Exercise 16



target = open(filename, 'w')



What does 'w' mean?

It's really just a string with a character in it for the kind of mode for the file. If you use 'w'then you're saying "open this file in 'write' mode," thus the 'w' character. There's also 'r' for "read," 'a' for append, and modifiers on these.
Exercise 17

CODE

from_file, to_file = ARGV

puts "Copying from #{from_file} to #{to_file}"




in_file = open(from_file)


indata = in_file.read




puts "The input file is #{indata.length} bytes long"


puts "Does the output file exist? #{File.exist?(to_file)}"


puts "Ready, hit RETURN to continue, CTRL-C to abort."




$stdin.gets




out_file = open(to_file, 'w')out_file.write(indata)




puts "Alright, all done."


out_file.close


in_file.close

Exercise 17

File.exist?(to_file)

This can be broken down as, "File! I want you to use your exist? function to tell me if to_file exists on the disk." Yet another way to say this is, "Get the exist? function from File and call it with the variable to_file."
Exercise 18

What does a function do?

They name pieces of code the way variables name strings and numbers.



They take arguments the way your scripts take ARGV.




Using 1 and 2 they let you make your own "mini-scripts" or "tiny commands."

Exercise 18

How do you create a function?

You can create a function by using the word def in Ruby.

Exercise 18

Function pattern
def var(arg1, arg2)

puts "arg1: #{arg1}, arg2: #{arg2}"


end




var(input,input)

Exercise 18

Function Checklist

Did you start your function definition with def?

Does your function name have only characters and _ (underscore) characters?


Did you put an open parenthesis ( right after the function name?


Did you put your arguments after the parenthesis ( separated by commas?


Did you make each argument unique (meaning no duplicated names)?


Did you put a close parenthesis ) after the arguments?


Did you indent all lines of code you want in the function two spaces?


Did you end your function with end lined up with the def above?

Exercise 18

When you run ("use" or "call") a function, check these things:



Did you call/use/run this function by typing its name?

Did you put the ( character after the name to run it?


Did you put the values you want into the parenthesis separated by commas?


Did you end the function call with a ) character?


Functions that don't have parameters do not need the () after them, but would it be clearer if you wrote them anyway?

Exercise 18

What's allowed for a function name?

The same as variable names. Anything that doesn't start with a number, and is letters, numbers, and underscores will work.
Exercise 18

What does the * in *args do?

That tells Ruby to take all the arguments to the function and then put them in args as a list. It's like argv that you've been using, but for functions. It's not normally used too often unless specifically needed.
Exercise 19

Are variable in your function connected to the variables in your script?



The variables in your function are not connected to the variables in your script.
Exercise 21



def add(a, b)


puts "ADDING #{a} + #{b}"


return a + b


end




age = add(30, 5)

Our function is called with two arguments: a and b.We print out what our function is doing, in this case "ADDING."Then we tell Ruby to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."Ruby adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.
Exercise 27

The Truth Terms

&& (and)

|| (or)


! (not)


!= (not equal)


== (equal)


>= (greater-than-equal)


<= (less-than-equal)


true


false

Exercise 27

The Truth Tables (Not)

NOT

!false == true


!true == false

Exercise 27 The Truth Tables ( OR)
OR (||)

true || false == true


true || true == true


false || true == true


false || false == false

Exercise 27 The Truth Tables (And )
AND (&&)

true && false == false


true && true == true


false && true == false


false && false == false

Exercise 27 The Truth Tables (NOT OR)
NOT OR

not (true || false) == false


not (true || true) == false


not (false || true) == false


not (false || false) == true

Exercise 27 The Truth Tables ( NOT AND )
NOT AND

!(true && false) == true


!(true && true) == false


!(false && true) == true


!(false && false) == true

Exercise 27 The Truth Tables ( != )
!=

1 != 0 == true


1 != 1 == false


0 != 1 == true


0 != 0 == false

Exercise 27 The Truth Tables ( == )
==

1 == 0 == false


1 == 1 == true


0 == 1 == false


0 == 0 == true

Exercise 28: Boolean Practice

true && true

true
Exercise 28: Boolean Practice

false && true

false
Exercise 28: Boolean Practice

1 == 1 && 2 == 1

false
Exercise 28: Boolean Practice

"test" == "test"

true?
Exercise 28: Boolean Practice

1 == 1 || 2 != 1

true
Exercise 28: Boolean Practice

true && 1 == 1

true
Exercise 28: Boolean Practice

false && 0 != 0

false?
Exercise 28: Boolean Practice

true || 1 == 1

true
Exercise 28: Boolean Practice

"test" == "testing"

false
Exercise 28: Boolean Practice

1 != 0 && 2 == 1

false
Exercise 28: Boolean Practice

"test" != "testing"

true
Exercise 28: Boolean Practice

"test" == 1

false
Exercise 28: Boolean Practice

!(true && false)

false
Exercise 28: Boolean Practice

!(1 == 1 && 0 != 1)

false?
Exercise 28: Boolean Practice

!(10 == 1 || 1000 == 1000)

true?
Exercise 28: Boolean Practice

!(1 != 10 || 3 == 4)

true?
Exercise 28: Boolean Practice

!("testing" == "testing" && "Zed" == "Cool Guy")

false?
Exercise 28: Boolean Practice

1 == 1 && (!("testing" == 1 || 1 == 0))

true?
Exercise 28: Boolean Practice

"chunky" == "bacon" && (!(3 == 4 || 3 == 3))

false?

Exercise 28: Boolean Practice

3 == 3 && (!("testing" == "testing" || "Ruby" == "Fun"))
false?
Exercise 28: Boolean Practice (trick)
Whenever you see these boolean logic statements, you can solve them easily by this simple process:



Find an equality test (== or !=) and replace it with its truth.


Find each &&/|| inside parentheses and solve those first.


Find each ! and invert it.


Find any remaining &&/|| and solve it.


When you are done you should have true or false.

Exercise 28: equality operators
Combined Operator

x += y == x = x + y


x -= y == x = x - y


x /= y == x = x / y


x *= y == x = x * y


x %= y == x = x % y


x **= y == x = x ** y

Exercise 28: equality operators
==Tests for equality.Returns true or false

.eql? Same as ==.


!= Tests for inequality. Returns true for inequality or false for equality


< Less than. Returns true if first operand is Less than second operand. Otherwise returns false.




> Greater than. Returns true if first operand is greater than second operand. Otherwise returns false.




>= Greater than or equal to. Returns true if first operand is greater than or equal to second operand. Otherwise returns false.




<= Less than or equal to. Returns true if first operand is less than or equal to second operand. Otherwise returns false.<=>Combined comparison operator. Returns 0 if first operand equals second, 1 if first operand is greater than the second and -1 if first operand is less than the second.

Exercise 29: If statement
people = 20

cats = 30


dogs = 15




if people < cats


puts "Too many cats! The world is doomed!"end




if people > cats


puts "Not many cats! The world is saved!"end


if people < dogs


puts "The world is drooled on!"


end


if people > dogs


puts "The world is dry!"


end

Exercise 30 :

What do you think the if does to the code under it?

An if-statement creates what is called a "branch" in the code. It's kind of like those choose your own adventure books where you are asked to turn to one page if you make one choice, and another if you go a different direction. The if-statement tells your script, "If this boolean expression is true, then run the code under it, otherwise skip it."
Exercise 30 :

Why does the code under the if need to be indented two spaces?

In Ruby you indent code under statements like if, else, and others so that other programmers know it is a "block" of code. Blocks can have other blocks in them and are ended with an end. There are other ways to make a block of code, but for if-statements this is the way.
Exercise 30 :

What happens if you don't end it with end?

If you don't then Ruby doesn't know where your if-statement ends and where others might begin, so it will give you a syntax error.
Exercise 30 :

code

people = 30

cars = 40


trucks = 15




if cars > people


puts "We should take the cars."


elsif cars < people


puts "We should not take the cars."


else


puts "We can't decide."


end

Exercise 30 :

What happens if multiple elsif blocks are true?

Ruby starts and the top runs the first block that is true, so it will run only the first one.
Exercise 31 Making Decisions
In the first half of this book you mostly just printed out things called functions, but everything was basically in a straight line. Your scripts ran starting at the top and went to the bottom where they ended. If you made a function you could run that function later, but it still didn't have the kind of branching you need to really make decisions. Now that you have if, else, and elsif you can start to make scripts that decide things.
Exercise 31

Can you replace elsif with a sequence of if-else combinations?

You can in some situations, but it depends on how each if/else is written. It also means that Ruby will check every if-else combination, rather than just the first false ones like it would with if-elsif-else. Try to make some of these to figure out the differences.

Exercise 31

What if I wanted more options in the if-elsif-else blocks?
Add more elsif blocks for each possible choice.
Exercise 32

for-loop

However, programs also need to do repetitive things very quickly
Exercise 32

arrays

Before you can use a for-loop, you need a way to store the results of loops somewhere. The best way to do this is with arrays. Arrays are exactly what their name says: a container of things that are organized in order from first to last. It's not complicated; you just have to learn a new syntax. First, there's how you make arrays:
Exercise 32 First, there's how you make arrays:
hairs = ['brown', 'blond', 'red']

eyes = ['brown', 'blue', 'green']


weights = [1, 2, 3, 4]

Exercise 32 First, there's how you make arrays:
You start the array with the [ (left bracket) which "opens" the array. Then you put each item you want in the array separated by commas, similar to function arguments. Lastly, end the array with a ] (right bracket) to indicate that it's over. Ruby then takes this array and all its contents and assigns them to the variable.

Exercise 36


Rules for If-Statements

Every if-statement must have an else.If this else should never run because it doesn't make sense, then you must use adie function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.Never nest if-statements more than two deep and always try to do them one deep.Treat if-statements like paragraphs, where each if-elsif-else grouping is like a set of sentences. Put blank lines before and after.Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.
Exercise 36

Rules for Loops

Use a while-loop only to loop forever, and that means probably never. This only applies to Ruby; other languages are different.Use a for-loop for all other kinds of looping, especially if there is a fixed or limited number of things to loop over.
Exercise 36

Tips for Debugging

Do not use a "debugger." A debugger is like doing a full-body scan on a sick person. You do not get any specific useful information, and you find a whole lot of information that doesn't help and is just confusing.The best way to debug a program is to use put to print out the values of variables at points in the program to see where they go wrong.Make sure parts of your programs work as you work on them. Do not write massive files of code before you try to run them. Code a little, run a little, fix a little.


Exercise 36

The best way to work on a piece of software is in small chunks like this:

On a sheet of paper or an index card, write a list of tasks you need to complete to finish the software. This is your to do list.Pick the easiest thing you can do from your list.Write out English comments in your source file as a guide for how you would accmplish this task in your code.Write some of the code under the English comments.Quickly run your script so see if that code worked.Keep working in a cycle of writing some code, running it to test it, and fixing it until it works.Cross this task off your list, then pick your next easiest task and repeat.

This process will help you work on software in a methodical and consistent manner. As you work, update your list by removing tasks you don't really need and adding ones you do.

Exercise 37: Symbol Review



BEGIN

Run this block when the script starts.

BEGIN { puts "hi" }

Exercise 37: Symbol Review


END

Run this block when the script is done.


END { puts "hi" }

Exercise 37: Symbol Review


alias

Create another name for a function.


alias X Y

Exercise 37: Symbol Review


and

Logical and, but lower priority than &&


puts "Hello" and "Goodbye"

Exercise 37: Symbol Review


begin

Start a block, usually for exceptions.


begin end

Exercise 37: Symbol Review


break

Break out of a loop right now.


while true; break; end

Exercise 37: Symbol Review


case

Case style conditional, like an if.


case X; when Y; else; end

Exercise 37: Symbol Review


class

Define a new class.


class X; end

Exercise 37: Symbol Review


def

Define a new function.


def X(); end

Exercise 37: Symbol Review


defined?

Is this class/function/etc. defined already?


defined? Class == "constant"

Exercise 37: Symbol Review


do

Create a block that maybe takes a parameter.


(0..5).each do |x| puts x end

Exercise 37: Symbol Review


else

Else conditional.


if X; else; end

Exercise 37: Symbol Review


elsif

Else if conditional


if X; elsif Y; else; end

Exercise 37: Symbol Review


end

Ends blocks, functions, classes, everything.


begin end # many others

Exercise 37: Symbol Review


ensure

Run this code whether an exception happens or not.


begin ensure end

Exercise 37: Symbol Review


for

For loop syntax. The .each syntax is preferred.


for X in Y; end

Exercise 37: Symbol Review


if

If conditional.


if X; end

Exercise 37: Symbol Review


in

n part of for-loops.


for X in Y; end

Exercise 37: Symbol Review


module

Define a new module.


module X; end

Exercise 37: Symbol Review


next

Skip to the next element of a .each iterator.


(0..5).each {|y| next }

Exercise 37: Symbol Review


not

Logical not. But use ! instead.


not true == false

Exercise 37: Symbol Review


or

Logical or.


puts "Hello" or "Goodbye"

Exercise 37: Symbol Review


redo

Rerun a code block exactly the same.


(0..5).each {|i| redo if i > 2}

Exercise 37: Symbol Review


rescue

Run this code if an exception happens.


begin rescue X; end

Exercise 37: Symbol Review


retry

In a rescue clause, says to try the block again.


0..5).each {|i| retry if i > 2}

Exercise 37: Symbol Review


return

Returns a value from a function. Mostly optional.


return X

Exercise 37: Symbol Review


self



The current object, class, or module.


defined? self == "self"

Exercise 37: Symbol Review


super

The parent class of this class.


super



Exercise 37: Symbol Review


then

Can be used with if optionally.


if true then puts "hi" end

Exercise 37: Symbol Review


undef

Remove a function definition from a class.


undef X

Exercise 37: Symbol Review


unless

nverse of if.


unless false then puts "not" end



Exercise 37: Symbol Review


until

qInverse of while, execute block as long as false.


until false; end

Exercise 37: Symbol Review


when

Part of case conditionals.


case X; when Y; else; end

Exercise 37: Symbol Review


while

While loop.


while true; end

Exercise 37: Symbol Review


yield

Pause and transfer control to the code block.


yield

Exercise 37: Symbol Review


Data Types


true

True boolean value.


true or false == true

Exercise 37: Symbol Review Data Types


false

False boolean value.


false and true == false



Exercise 37: Symbol Review Data Types


nil

Represents "nothing" or "no value".


x = nil

Exercise 37: Symbol Review Data Types


strings

Stores textual information.


x = "hello"



Exercise 37: Symbol Review Data Typesnumbers

Stores integers.


i = 100



Exercise 37: Symbol Review Data Types


floats

Stores decimals.


i = 10.389

Exercise 37: Symbol Review Data Types


arrays

Stores a list of things.


j = [1,2,3,4]



Exercise 37: Symbol Review Data Types


hashes

Stores a key=value mapping of things.


e = {'x' => 1, 'y' => 2}

Exercise 37: Symbol Review


String Escape Sequences


\\

Backslash

Exercise 37: Symbol Review String Escape Sequences


\'

Single-quote



Exercise 37: Symbol Review String Escape Sequences


\"

Double-quote

Exercise 37: Symbol Review String Escape Sequences


\a

Bell

Exercise 37: Symbol Review String Escape Sequences


\b

Backspace

Exercise 37: Symbol Review String Escape Sequences


\f

Formfeed

Exercise 37: Symbol Review String Escape Sequences


\n

Newline

Exercise 37: Symbol Review String Escape Sequences


\r

Carriage

Exercise 37: Symbol Review String Escape Sequences


\t

Tab

Exercise 37: Symbol Review String Escape Sequences


\v

Vertical tab

Exercise 37: Symbol Review


Operators


+

Add


2 + 4 == 6

Exercise 37: Symbol Review Operators


-

Subtract


2 - 4 == 2

Exercise 37: Symbol Review Operators


*

Multiply


2 * 4 == 8

Exercise 37: Symbol Review Operators


**

Power of


2 ** 4 == 16

Exercise 37: Symbol Review Operators


/

Divide


2 / 4.0 == 0.5

Exercise 37: Symbol Review Operators


%

Modulus


2 % 4 == 2

Exercise 37: Symbol Review Operators


>

Greater than

Exercise 37: Symbol Review Operators


.

Dot access


"1".to_i == 1

Exercise 37: Symbol Review Operators


::

Colon access


Module::Class



Exercise 37: Symbol Review Operators


[]

List brackets


[1,2,3,4]

Exercise 37: Symbol Review Operators


!

Not


!true == false

Exercise 37: Symbol Review Operators


<

Less than

Exercise 37: Symbol Review Operators


>=

Greater than equal

Exercise 37: Symbol Review Operators


<=

Less than equal

Exercise 37: Symbol Review Operators


<=>

Comparison

Exercise 37: Symbol Review Operators


==

Equal

Exercise 37: Symbol Review Operators


===

Equality

Exercise 37: Symbol Review Operators


!=

Not equal

Exercise 37: Symbol Review Operators


&&

Logical and (higher precedence)

Exercise 37: Symbol Review Operators


||

Logical or (higher precedence)

Exercise 37: Symbol Review Operators


..

Range inclusive


(0..3).to_a == [0, 1, 2, 3]

Exercise 37: Symbol Review Operators


...

Range non-inclusive


(0...3).to_a == [0, 1, 2]

Exercise 37: Symbol Review Operators


@

Object scope


@var ; @@classvar

Exercise 37: Symbol Review Operators


@@

Class scope


@var ; @@classvar

Exercise 37: Symbol Review Operators


$

Global scope


$stdin



Exercise 37: Symbol Review


Reading Code

First, print out the code you want to understand. Yes, print it out, because your eyes and brain are more used to reading paper than computer screens. Make sure you print a few pages at a time.

Exercise 37: Symbol Review Reading Code


Second, go through your printout and take notes of the following:

Functions and what they do.Where each variable is first given a value.Any variables with the same names in different parts of the program. These may be trouble later.Any if-statements without else clauses. Are they right?Any while-loops that might not end.Any parts of code that you can't understand for whatever reason.

Exercise 37: Symbol Review Reading Code


Third

Third, once you have all of this marked up, try to explain it to yourself by writing comments as you go. Explain the functions, how they are used, what variables are involved and anything you can to figure this code out.

Exercise 37: Symbol Review Reading Code


Last

Lastly, on all of the difficult parts, trace the values of each variable line by line, function by function. In fact, do another printout and write in the margin the value of each variable that you need to "trace."

Exercise 37: Symbol Review Reading Code


last 2



Once you have a good idea of what the code does, go back to the computer and read it again to see if you find new things. Keep finding more code and doing this until you do not need the printouts anymore.

Exercise 37: Symbol Review Reading Code


Find out what a "flow chart"



Exercise 38: Doing Things to Arrays




When you write mystuff.push('hello') you are actually setting off a chain of events inside Ruby to cause something to happen to the mystuff array. Here's how it works:

Ruby sees you mentioned mystuff and looks up that variable. It might have to look backward to see if you created with =, if it is a function argument, or if it's a global variable. Either way it has to find the mystuff first.Once it finds mystuff it reads the . (period) operator and starts to look at variablesthat are a part of mystuff. Since mystuff is an array, it knows that mystuff has a bunch of functions.It then hits push and compares the name to all the names that mystuff says it owns. If push is in there (it is) then Ruby grabs that to use.Next Ruby sees the ( (parenthesis) and realizes, "Oh hey, this should be a function." At this point it calls (runs, executes) the function just like normally, but instead it calls the function with an extra argument.That extra argument is ... mystuff! I know, weird, right? But that's how Ruby works so it's best to just remember it and assume that's the result. What happens, at the end of all this, is a function call that looks like: push(mystuff, 'hello') instead of what you read which is mystuff.append('hello').



Exercise 38: Doing Things to Arrays




Data Structure

Let's say you want to create a computer game based on Go Fish. If you don't know what Go Fish is, take the time now to go read up on it on the internet. To do this you would need to have some way of taking the concept of a "deck of cards" and put it into your Ruby program. You then have to write Ruby code that knows how to work this imaginary version of a deck of cards so that a person playing your game thinks that it's real, even if it isn't. What you need is a "deck of cards" structure, and programmers call this kind of thing a "data structure".

Exercise 38: Doing Things to Arrays


What's a data structure?

If you think about it, a "data structure" is just a formal way to structure(organize) some data (facts). It really is that simple, even though some data structures can get insanely complex, all they are is just a way to store facts inside a program so you can access them in different ways. They structure data.

Exercise 38: Doing Things to Arrays



I'll be getting into this more in the next exercise, but arrays are one of the most common data structures programmers use. They are simply ordered lists of facts you want to store and access randomly or linearly by an index. What?! Remember what I said though, just because a programmer said "array is a list" doesn't mean that it's any more complex than what an array already is in the real world. Let's look at the deck of cards as an example of an array:

You have a bunch of cards with values.Those cards are in a stack, list, or array from the top card to the bottom card.You can take cards off the top, the bottom, the middle at random.If you want to find a specific card, you have to grab the deck and go through it one at a time.

Exercise 38: Doing Things to Arrays


Let's look at what I said:

"An ordered array"Yes, deck of cards is in order with a first, and a last."of things you want to store"Yes, cards are things I want to store."and access randomly"Yes, I can grab a card from anywhere in the deck."or linearly"Yes, if I want to find a specific card I can start at the beginning and go in order."by an index"Almost, since with a deck of cards if I told you to get the card at index 19 you'd have to count until you found that one. In our Ruby arrays the computer can just jump right to any index you give it.

Exercise 38: Doing Things to Arrays


When to Use Arrays

ou use an array whenever you have something that matches the array data structure's useful features:If you need to maintain order. Remember, this is listed order, not sorted order. Arrays do not sort for you.If you need to access the contents randomly by a number. Remember, this is usingcardinal numbers starting at 0.If you need to go through the contents linearly (first to last). Remember, that's whatfor-loops are for.