Case Statements

I am continuing along on learning Ruby. Today, it’s a dive into case statements!

So, case statements are used to run multiple conditions against one value. To create a case statements you need:

  1. a value
  2. one or more conditions to compare the value to
  3. code to run if the condition is met

Case statements are useful when you have have a list of possible conditions and you need your code to operate if the condition is met. Consider this:

I mean, the above works but it is needlessly complex. Flatiron called it “code smell,” a phrase I am completely unfamiliar with but makes sense. We can do this better with a case statement. Let’s take a look:

So, let’s examine what we did! First we create the value we are testing

Then adding in conditions:

In the above, the name passed in will be tested against the condition and then, in this last part, if it meets it it will execute that code.

And, as seen above, we can add an else at the end that will run when no case value is met!

Scoping Out Method Scopes

I have finally returned to Ruby and none too soon! Today, lets look at scopes in Ruby.

The scope of a program means that the variables we create do not exist everywhere in a program. This helps in preventing the programmer from overwriting a variable created by someone else (or, let’s be honest, themselves) in other parts of a program. I mean, it could still happen, but it reduces the risk.

Methods have their own scope. A variable created outside a method is unavailable to the method. This means if we set a variable outside of a method, and then create a method with variables inside that method, the variables outside the method are not accessible inside the method and vice versa. Let’s look at an example:

Now, in the above I have defined a variable outside of the method, my_name, and set it equal to Nick. When I run the Ruby file I get the immediate response below the defined method, #greeting, that puts the my_name variable to the screen. It also returns nil. Below that I call the #greeting method and pass in the argument “Sophie” which runs and spits out an error.

See here:

So, we see that outside the method that my_name variable is accessible. Inside the method, however, my_name is inaccessible. Let’s try something a little different. What if I have this?

What will happen? If you run the file, my_name variable will be puts to the screen and then we get an error. See here:

At this point the program stops, thus #greeting method is never called. Why? Because inside_voice is a method scope variable and inaccessible outside of it.

A Look at Ruby Methods, Loops, and Logic

As my last post noted, I am currently enrolled at Flatiron School’s Online Community-Powered Bootcamp. It has been a great experience thus far. This blog has always been a place for me to note my studies and thoughts about what I’m learning. I have discovered over the time I’ve been here that others also have come by to enhance their learning, and for that I’m grateful and happy.

As such, I will be blogging here again regularly. My last post prior to this resurgence was in 2015. I was not inactive, per se, but I slowly became more active as 2016 went on. I was embroiled in the election, and once it began wrapping up I started studying again. I went through the Web Dev Bootcamp’s Javascript section and built a few of the #Javascript30 projects but I missed Ruby on Rails. I looked at a few options before settling on the Flatiron program. While the price is a big commitment, but I am committed to make this change.

I will be mostly using this as a way to look at the code I’m writing as I complete projects for this bootcamp and explaining what I’m doing. One of the things I like is that I’m not just being told “type this” and blindly mimicking code. I actually have to sit down and write the code. So, this is all code I’ve written.

So, this first section is an intro to Ruby. I’ve learned about variables, methods, logic and conditions, boolean, and loops. I also learned, for the first time, about command line applications. So, I’m going to post the code I have written up to a lesson that looks at taking a turn in the tic tac toe app we are building and break it down. First, I’ll post the bin file, turn,

and now, the Ruby turn.rb file.

So, first and foremost, a command line application, called a CLI for command line interface, is a file that the user launches to run the application from the command line. No graphics here. This is called the bin file, and is stored in the bin directory in our application. This is the executable file we run our program from. Let’s go through this file line by line. I’ll post it again:

Ok, the first line is known as the shebang line:

This tells the interpreter to use Ruby as the language for the file.

Next, we tell the bin file to require the turn.rb file with this line:

This gives us access to methods we define in that file. This will be important in just a minute.

Now, we are going to create an array called board and set it up with some strings with a space in them:

And then greet the user and call two methods from the turn.rb file. Both will pass in board as an argument:

OK, now that we are through the bin file, let’s look at the turn.rb file in more depth. This file is located in the lib directory. I’ll put the whole thing here for reference, but then pull out each method individually as we go through it:

Let’s break this down. First, we call a method titled display_board that accepts one argument, the array we defined in the bin file. This method will build the frame of our tic tac toe board.

When we run the app, it will display like this:

Very high res, HD graphics!

Inside each puts call, you will notice these:

This is a string interpolation. Basically, this allows us to put the variable inside of the string. This in particular is pulling the data from the array. As the game is played the users will place their X and O markers in the 9 quadrants of the tic tac toe board. They will be asked to select a space numbered 1 to 9, with 1 being the top left corner and 9 being the bottom right corner. The X’s and O’s will be put inside the array in the necessary spots, and then the display_board method will interpolate the marker as it is updated.

Next, let’s look at the turn method, and as we go through it we will discuss the methods that are called from inside it. First, the method:

So, this again takes the argument of board. It asks the user, as we discussed above, to choose a space from 1 to 9 and then takes the input using the gets method. gets will take the users input, and then, using the strip method will remove any new lines or trailing whitespace. Next, this input is sent to another method defined called input_to_index:

This method will first take the argument input and turn it into an integer with the to_i method then it subtracts 1 from it. This is because the array starts counting at 0, while we are asking the user to start counting the quadrants at 1. so, while the top left square in the array is 0, the user is entering 1. Subtracting 1 fixes this. Let’s return now back to the turn method.

We are now going to define a new variable, m, and have this variable decide whether the move made by the user is a valid move. This is calling another method, valid_move?, which is below, along with it’s helper method, position_taken?:

It will probably be best to start looking at position_taken? first. This takes two arguments, the board array and the index we just created with the input_to_index method. It uses an if statement to decide whether the position the user has chosen is taken already. So, the first part of the method asks “if the spot on the board is empty then return false (the position is NOT taken), then the next part says “else, if there is an X or O already there, return true (the position IS taken). Notice here that we are using the || for the boolean for “or”.

Now, looking at this, we return to the valid_move? method. This method is deciding whether the move the user made is valid. If the user tries to take a position already taken it is not valid, hence we utilize the position_taken? method we just discussed. It also looks at a range to ensure the user is playing on the board and not in a position elsewhere. This utilizes the between? method which passes in to arguments, the start and end of the numeric range which here is 0-8. Notice also that the if statement is using && for an “and” comparison, as well as the ! in front of position_taken? to make it negative, reading instead “position is not taken.” So, this method is literally saying “if the move is between 0-8 and the position is NOT taken, its a valid move, otherwise it is not a valid move.”

So, moving forward in the turn method, the move we asked the user to make is validated through the valid_move? method. If the move is valid, which returns true, then we allow the move to proceed via the move method. Here it is:

This brings in three arguments, the board array, the index and the char argument which is the X or O for each user. Currently, the char is set to X as a default argument. Soon, it will allow the O character. This method takes the index we created from the users input and places the X on the position they chose, updating the board array.

If the move is not valid, a loop is called. Let me place this part below so we can walk through it.

So, first, m enters here as false. The loop states “until m is true, this loop will keep coming around.” The user is told the move was invalid and prompted to enter another move. The input is taken through all of the above methods we discussed again and if the move is valid, the loop ends. If not, we go through until it is valid.

Here is what we are hoping happens:

And here it is with me choosing an invalid position:

This time I showed where I called the bin using ruby bin/turn. I made the move, picking a position WAY off the board, and then the app told me the move was invalid and prompted me again. This time I got it right and the lower left hand corner had an X added to it.

I hope this helps anyone visiting to understand Ruby methods, loops, and logic a bit better. If you have questions, feel free to ask!

 

Day 28: Part, Two: Some Treehouse

OK, its late and it was a long day but I am committed to continuing. Let’s get to it:

Video 1: Variables

Here is the code. Note that this is the same name.rb file from the last Ruby lesson at Treehouse. We also changed the way the puts statements at the end were written:

And the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby name.rb
Mr. Nick Teddy Queen

Challenge Task 1 of 4

In the initialize method of the Name class, set an instance variable called @title to the title argument. Note: you will have to write the initialize method.

Challenge Task 2 of 4

Below the Name class, instantiate a new Name instance set to the variable name with any title you choose.

Challenge Task 3 of 4

Inside the Name class, create a method called title that returns the @title variable.

Challenge Task 4 of 4

Call the title method on the name instance.

Video 2: Attribute Readers

The code:

Wow. That is a really neat code!

The result is the same:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby name.rb
Mr. Nick Teddy Queen

Challenge Task 1 of 1

In the Name class, create an attr_reader for the title instance variable.

Video 3: Attribute Writers and Accessors

First some work in IRB:

And having not been able to give myself a doctorate, we need to go into the file and fix this travesty!

OR, we can use attr_writer, and past that, attr_accessor which does reader and writer:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby name.rb
Mr. Nick Teddy Queen
Title: Mr.
Title: Dr.

Challenge Task 1 of 2

In the Name class, create an attr_writer for the first_name instance variable.

Challenge Task 2 of 2

In the Name class, create an attr_accessor for the last_name instance variable.

And that is it for tonight. I am halfway through this stage. Will finish tomorrow!

Day 28, Part One: Exercise 33 of Learn Ruby the Hard Way

I have some time before work so want to keep studying!

Time for Exercise 33: While Loops

And the result:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex33.rb
At the top is 0
Numbers now:
0
At the bottom i is 1
At the top is 1
Numbers now:
0
1
At the bottom i is 2
At the top is 2
Numbers now:
0
1
2
At the bottom i is 3
At the top is 3
Numbers now:
0
1
2
3
At the bottom i is 4
At the top is 4
Numbers now:
0
1
2
3
4
At the bottom i is 5
At the top is 5
Numbers now:
0
1
2
3
4
5
At the bottom i is 6
The numbers:
0
1
2
3
4
5

And on to the study drills:

1. Convert this while-loop to a function that you can call, and replace 6 in the test (i < 6) with a variable.

This was hard. I ended up writing it through twice and having to go back to read the function lessons again. My first try I got this error:

Basically, it tells me I was not passing in the correct number of arguments. I was trying to define i in the function. I took that out and then called the arguments correctly, which looks like this:

And to my surprise it works! This is so important to me. I have had doubts that I was just mimicing what I read and not really learning. I had that initial feeling of “oh crap,” seeing this study drill. I then slowed down and thought through it. I read back over past lessons. I knew I had to use def and then just write inside it the while loop. From there I tweaked until it worked. And it did!

The results:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby studydrill33.rb
At the top is 0
Numbers now:
0
At the bottom i is 1
At the top is 1
Numbers now:
0
1
At the bottom i is 2
At the top is 2
Numbers now:
0
1
2
At the bottom i is 3
At the top is 3
Numbers now:
0
1
2
3
At the bottom i is 4
At the top is 4
Numbers now:
0
1
2
3
4
At the bottom i is 5
At the top is 5
Numbers now:
0
1
2
3
4
5
At the bottom i is 6

2. Use this function to rewrite the script to try different numbers.

The great thing with functions is that you can quickly change the arguments you pass to them. I went ahead and added a second argument to the function, removing widgets from inside it and passing it through in an argument. I then tried it and here is the result:

The code:

Here is the result:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby studydrill33.rb
At the top is 3
Numbers now:
3
At the bottom i is 4
At the top is 4
Numbers now:
3
4
At the bottom i is 5
At the top is 5
Numbers now:
3
4
5
At the bottom i is 6
At the top is 6
Numbers now:
3
4
5
6
At the bottom i is 7
At the top is 7
Numbers now:
3
4
5
6
7
At the bottom i is 8
At the top is 8
Numbers now:
3
4
5
6
7
8
At the bottom i is 9
At the top is 9
Numbers now:
3
4
5
6
7
8
9
At the bottom i is 10
At the top is 10
Numbers now:
3
4
5
6
7
8
9
10
At the bottom i is 11
At the top is 11
Numbers now:
3
4
5
6
7
8
9
10
11
At the bottom i is 12
At the top is 12
Numbers now:
3
4
5
6
7
8
9
10
11
12
At the bottom i is 13
At the top is 13
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
At the bottom i is 14
At the top is 14
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
At the bottom i is 15
At the top is 15
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
15
At the bottom i is 16
At the top is 16
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
At the bottom i is 17
At the top is 17
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
At the bottom i is 18
At the top is 18
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
At the bottom i is 19
At the top is 19
Numbers now:
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
At the bottom i is 20

I am amazed that I am finally getting this more and more. Yay!

3. Add another variable to the function arguments that you can pass in that lets you change the + 1 on line 8 so you can change how much it increments by. and 4. Rewrite the script again to use this function to see what effect that has.

The code:

The result:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby studydrill33.rb
At the top is 3
Numbers now:
3
At the bottom i is 7
At the top is 7
Numbers now:
3
7
At the bottom i is 11
At the top is 11
Numbers now:
3
7
11
At the bottom i is 15
At the top is 15
Numbers now:
3
7
11
15
At the bottom i is 19
At the top is 19
Numbers now:
3
7
11
15
19
At the bottom i is 23

And that is all the time I have. I will continue at the end of this exercise when I return later! So excited!

Return of Day 27: Back in the Treehouse

So, I have a little more time and decided to work on a little Treehouse.

Video 1: Ruby Classes

And this is just an overview of the idea of Ruby classes, which I covered in Michael Hartl’s tutorial.

Video 2: Instantiation

OK, this goes a little deeper. We discuss creating new objects and the difference between classes and instances. The act of creating an instance of a class is called instantiation. Once created, that instance is called an object. Take a look at the irb session below:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ irb
>> string = String.new
=> “”
>> string.class
=> String
>> nick = String.new(“Nick”)
=> “Nick”
>> Array.new
=> []
>> Hash.new
=> {}
>> exit

And then some code:

And the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby myclass.rb
This is the initialize method.

And the challenge:

Challenge Task 1 of 2

Instantiate a new instance of the String class and assign the newly instantiated instance to the variable string.

Challenge Task 2 of 2

Instantiate a new instance of the Array class and assign the newly instantiated instance to the variable array.

Video 3: Ruby Objects

So, object oriented programming. I have heard of it a lot but this was the first direct discussion of it.

Challenge Task 1 of 1

Using the respond_to? method, ask the string variable if it responds to the upcase method. Remember, the respond_to? method can take a string or a symbol as an argument.

Video 4: Creating a Class

The one thing I can say I like about TreeHouse is that it gives the lessons in nice, bite-sized chunks but that they are also easy to follow, even when really difficult stuff. This isn’t necessarily difficult, and it may be because its my second time doing this, but I am beginning to understand the idea of creating a class.

The code:

So, we create a class named “Name” and then defined three methods underneath it, and then called them.

This is the location in Ruby of what we created:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby name.rb
#

and here we run it and call each method:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby name.rb
Mr.
Nick
Teddy
Queen

Challenge Task 1 of 3

Instantiate an instance of the Name class and assign it to the variable name. This must come after the definition of the Name class.

Challenge Task 2 of 3

Call the puts method with the name variable’s first_name method as an argument.

Challenge Task 3 of 3

On the next line, call the puts method with the name variable’s last_name method as an argument.

Another badge!

Day 27: A Short Evening of Study

A long day of work and company coming on Thursday night which I need to do some housework to prepare for means I will have a few short nights of study. Today I am focusing on Learn Ruby the Hard Way, Exercise 32: Loops and Arrays.

Here is the code from the lesson:

And the result:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex32.rb
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quarters
adding 0 to the list.
adding 1 to the list.
adding 2 to the list.
adding 3 to the list.
adding 4 to the list.
adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

And the study drills:

1. Take a look at how you used (0..5) in the last for-loop. Look up Ruby’s “range operator” (.. and …) online to see what it does.

I worked with ranges at TreeHouse and I feel pretty familiar with with what it does. Read more about ranges here.

2. Change the first for number in the_count to be a more typical .each style loop like the others.

OK. I did this:

and it worked!!!!

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex32.rb
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quarters
adding 0 to the list.
adding 1 to the list.
adding 2 to the list.
adding 3 to the list.
adding 4 to the list.
adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

3. Find the Ruby documentation on arrays and read about them. What other operations can you do besides the push function? Try <<, which is the same as push but is an operator. fruits << x is the same as fruits.push(x).

And it works. It is near the end. I actually thought I screwed up, broke it to make it mess up and redid it. I was shocked I got it right. I remember it from TreeHouse but it was a vague memory.

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex32.rb
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got pennies
I got 2
I got dimes
I got 3
I got quarters
adding 0 to the list.
adding 1 to the list.
adding 2 to the list.
adding 3 to the list.
adding 4 to the list.
adding 5 to the list.
Element was: 0
Element was: 1
Element was: 2
Element was: 3
Element was: 4
Element was: 5

And that is it tonight!

Day 26, Part 2: Some More Treehouse and a Recap

So, first, a recap of my current efforts:

  1. I started on May 27, 2015 with Codecademy HTML and CSS course and then moved on to Michael Hartl’s Ruby on Rails tutorial. I decided after Chapter 4 that i would focus on building up my Ruby proficiency and then return to it.
  2. I went from there to Zed Shaw’s Learn Ruby the Hard Way. I am currently on Exercise 32: Loops and Arrays.
  3. I have also signed up for TreeHouse and I am in my free month at present. I just added a widget with all the badges in the sidebar.
  4. My plan is to return to Hartl’s Ruby on Rails tutorial after completing TreeHouse’s Ruby portion and Learn Ruby the Hard Way.

So, tonight I plan to finish another portion of the TreeHouse Ruby track.

First video tonight is: Part 1: Asking Questions.

The code:

and the results:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby contact_list.rb
What is your name? Nick
Nick

Challenge Task 1 of 1

Fill out the parse_answer method to return the answer passed in. If the kind is number, convert it to an integer using the to_i method before returning it.

Next video: Part 2: Adding Contacts

The code:

and the results:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby contact_list.rb
What is the person’s name? Nick
Do you want to add a phone number? (y/n) y
Enter a phone number: 555
Do you want to add a phone number? (y/n) y
Enter a phone number: 454
Do you want to add a phone number? (y/n) 343
Do you want to add a phone number? (y/n) y
Enter a phone number: 654
Do you want to add a phone number? (y/n) n
Add another? (y/n) y
What is the person’s name? Jason
Do you want to add a phone number? (y/n) y
Enter a phone number: 765
Do you want to add a phone number? (y/n) n
Add another? (y/n) n

Challenge Task 1 of 3

Assign the value of the key name to the return value of the method get_name() in the contact hash. Assume that get_name() returns a string.

I had to look up an explanation for this one and found others found it confusing. Here is the answer:

This has to do with assigning the get_name() as the return value in the hash.

Key-Values Pairs : Hash = { KEY, VALUES }

Weird, and I think it was worded weirdly.

Challenge Task 2 of 3

Assign the value of the key phone_number to the return value of the method get_phone_number() in the contact hash. Assume that get_phone_number() returns a string.

Hmm. Again, the same.

Challenge Task 3 of 3

Append the contact hash to the contact_list array.

Last video: Part 3: Printing The Contact List

The code:

And results:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby contact_list.rb
What is the person’s name? Nick
Do you want to add a phone number? (y/n) y
Enter a phone number: 787
Do you want to add a phone number? (y/n) n
Add another? (y/n) y
What is the person’s name? Jason
Do you want to add a phone number? (y/n) y
Enter a phone number: 765
Do you want to add a phone number? (y/n) y
Enter a phone number: 987
Do you want to add a phone number? (y/n) n
Add another? (y/n) y
What is the person’s name? Ryan
Do you want to add a phone number? (y/n) y
Enter a phone number: 897
Do you want to add a phone number? (y/n) n
Add another? (y/n) n
___
Name: Nick
Phone: 787
___
Name: Jason
Phone: 765
Phone: 987
___
Name: Ryan
Phone: 897

Challenge Task 1 of 1

Using the each method, iterate over the contact_list array. Assign each array item to the local variable contact in the block and print out the value of the name and phone_number keys.

And I am done for tonight!

Day 26, part 1: Getting in Some Coding in the Morning

I thought I would get some studying in before breakfast. (Note: I thought I published this earlier but guess not!) Let’s get to it:

Exercise 30: Else and If

This is now my third time doing if, elsif and else statements. It is starting to sink in!

and the results:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex30.rb
We should take the cars.
Maybe we could take the trucks.
Alright, let’s just take the trucks.

1. Try to guess what elsif and else are doing.

It does different branches in the code. It provides different options depending on if the criteria is met.

2. Change the numbers of cars, people, and trucks and then trace through each if-statement to see what will be printed.

So, I switched the numbers around:

And here is the result, with the old results in italics:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex30.rb
We should take the cars.
Maybe we could take the trucks.
Alright, let’s just take the trucks.

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex30.rb
We should not take the cars.
That’s too many trucks.
Alright, let’s just take the trucks.

3. Try some more complex boolean expressions like cars > people || trucks < cars.

OK. Here is the code:

people = 60
cars = 52
trucks = 50

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 if trucks > cars
puts “That’s too many trucks.”
elsif trucks < cars puts "Maybe we could take the trucks." else puts "We still can't decide." end if cars < people && trucks < people puts "Blame management." else puts "Fine, let's stay home them." end and the result:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex30.rb
We should not take the cars.
Maybe we could take the trucks.
Blame management.

4. Above each line write an English description of what the line does.

Exercise 31: Making Decisions

OMG we are writing an adventure! And Cthulhu!

And a bunch of results because there is a lot here.

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There’s a giant bear eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 1
The bear eats your face off. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There’s a giant bear eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 2
The bear eats your legs off. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 1
There’s a giant bear eating a cheese cake. What do you do?
1. Take the cake.
2. Scream at the bear.
> 3
Well, doing 3 is probably better. Bear runs away.
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu’s retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 1
Your body survives powered by a mind of jello. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu’s retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 2
Your body survives powered by a mind of jello. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 2
You stare into the endless abyss at Cthulhu’s retina.
1. Blueberries.
2. Yellow jacket clothespins.
3. Understanding revolvers yelling melodies.
> 3
The insanity rots your eyes into a pool of muck. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1 or door #2?
> 3
You stumble around and fall on a knife and die. Good job!

Study Drills:

1. Make new parts of the game and change what decisions people can make. Expand the game out as much as you can before it gets ridiculous.
2. Write a completely new game. Maybe you don’t like this one, so make your own. This is your computer, do what you want.

I did 1. but 2. will take some work. I really want to do this, however! Let’s add another door to the adventure!

And the results are:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1, door #2
or door #3?
> 3
You see a clown with an axe beckoning for you to come closer.
1. Go closer. Its a clown!
2. Use the clown repellent in your belt.
3. Try to run away!
> 1
The clown introduces you to his good buddy Abe the Axe. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1, door #2
or door #3?
> 3
You see a clown with an axe beckoning for you to come closer.
1. Go closer. Its a clown!
2. Use the clown repellent in your belt.
3. Try to run away!
> 2
You reach down to get the clown repellent but realize too late you are not Batman! Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1, door #2
or door #3?
> 3
You see a clown with an axe beckoning for you to come closer.
1. Go closer. Its a clown!
2. Use the clown repellent in your belt.
3. Try to run away!
> 3
You turn to run and see that Cthulu came to visit Bozo the clown. You sink to your knees in terror. Good job!
demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex31.rb
You enter a dark room with two doors. Do you go through door #1, door #2
or door #3?
> 3
You see a clown with an axe beckoning for you to come closer.
1. Go closer. Its a clown!
2. Use the clown repellent in your belt.
3. Try to run away!
> 6
Really, there is no good option, even 6 is bad.

And that is it until later. I want to get through

Day 25: Continuing to Learn Ruby the Hard Way in a Treehouse

I try to keep the titles interesting, but I am running out of ways to do such.

FYI, I had a lot of false starts. First time I sat down we ended up having a tornado warning where I live. Next time I finally settle down and my dog demands me take him for a walk. Thankfully, the rain had stopped. But when we got to the farthest reaches of the walk it begins a torrential downpour and soaked me completely.

During all of this I did finish Exercise 27: Memorizing Logic by creating flash cards in AnkiDroid. I will be studying them this week. So, on to Exercise 28: Boolean Practice.

In this lesson I have to guess what the answer to each of the posed Boolean problems will be and then run them. So, I will put a comment next to each and then see how I do!

Here are my guesses with the code:

and then I opened IRB and ran each. I did well and got them all. The last ones were mind-bending, but if you take your time they are doable.

demosthenes131@rails-tutorial:~/workspace $ irb
>> true && true
=> true
>> false && true
=> false
>> 1 == 1 && 2 == 1
=> false
>> “test” == “test”
=> true
>> 1 == 1 || 2 != 1
=> true
>> true && 1 == 1
=> true
>> false && 1 == 1
=> false
>> true || 1 == 1
=> true
>> “test” == “testing”
=> false
>> 1 != 0 && 2 == 1
=> false
>> “test” != “testing”
=> true
>> “test” == 1
=> false
>> !(true && false)
=> true
>> !(1 == 1 && 0 != 1)
=> false
>> !(10 == 1 || 1000 == 1000)
=> false
>> !(1 != 10 || 3 == 4)
=> false
>> !(“testing” == “testing” && “Zed” == “Cool Guy”)
=> true
>> 1 == 1 && (!(“testing” == 1 || 1 ==0))
=> true
>> “chunky” == “bacon” && (!(3 == 4 || 3 == 3))
=> false
>> 3 == 3 && (!(“testing” == “testing” || “Ruby” == “Fun”))
=> false

Study drill time!

1. and 2. here are a lot of operators in Ruby similar to != and ==. Try to find as many “equality operators” as you can. They should be like < or <=. Write out the names of each of these equality operators. For example, I call != "not equal."

Done this before. You have the following:

> Greater than
>= Greater than or equal to
< Less than <= Less than or equal to == Equal === Used in a case/ when control structure which we did in Treehouse a bit back && and || or ! not != not equal

3. Play with the Ruby by typing out new boolean operators, and before you press Enter try to shout out what it is. Do not think about it. Shout the first thing that comes to mind. Write it down, then press Enter, and keep track of how many you get right and wrong.

With my Treehouse experience I have been doing this a lot so I’m moving forward!

Exercise 29: What If

So, the nice thing is I have done this at the Hartl tutorial and the Treehouse lesson. The reinforcement in very important!

Here’s the code:

and the results:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex29.rb
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

And on to the study drills:

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

It asks Ruby to evaluate the problem asked of it, basically if the following is true, do this.

2. and 3. Why does the code under the if need to be indented two spaces? and What happens if it isn’t indented?

I am still getting used to the proper formatting, but basically, the indenting makes it readable to humans. Ruby will still run it the same, but the indenting makes the programmers life easier.

4. Can you put other boolean expressions from Exercise 27 in the if-statement? Try it.

Yep. For example:

Returns:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex29.rb
Too many cats! The world is doomed!
Not many cats! The world is saved!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.
demosthenes131@rails-tutorial:~/workspace/LRTHW $

5. What happens if you change the initial values for people, cats, and dogs?

It would change the outputs of the script. Here is an example:

and the results:

demosthenes131@rails-tutorial:~/workspace/LRTHW $ ruby ex29.rb
Not many cats! The world is saved!
The world is drooled on!
People are less than or equal to dogs.

And now on to Treehouse.

First video “Iteration With Each”

So, first we run this:

and get this:

treehouse:~/workspace$ ruby each.rb
The current item is 0.
The current item is 1.
The current item is 2.
The current item is 3.
The current item is 4.
The current item is 5.

Then we comment out a portion and write an each statement, like so:

and get the same results:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby each.rb
The current array item is: 0
The current array item is: 1
The current array item is: 2
The current array item is: 3
The current array item is: 4
The current array item is: 5

And we create a second set of code to show using the each method and addition:

and the results:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby each_addition.rb
The current item + 2 is 2.
The current item + 2 is 3.
The current item + 2 is 4.
The current item + 2 is 5.
The current item + 2 is 6.
The current item + 2 is 7.

Challenge Task 1 of 1

Using the each method, iterate over every item in the numbers array and print the item using the puts method.

Next video is “Hash Iteration.”

Here is the code:

and the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby hash_iteration.rb
The hash key is name and the value is Treehouse.
The hash key is location and the value is Portland, OR.
Key: name
Key: location
Value: Treehouse
Value: Portland, OR

Challenge Task 1 of 1

Using the each method, iterate over every item in the contact hash and print the key and value using the puts method.

And onward to “Times Iteration.”

Here is the first bit of code:

and the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby times.rb
Hello!
Hello!
Hello!
Hello!
Hello!

and the second bit of code, using the times method with arguments:

and the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby times_with_arguments.rb
Hello! 0
Hello! 1
Hello! 2
Hello! 3
Hello! 4

Challenge Task 1 of 1

Print anything to standard output using the puts method 5 times by calling the times method on the number 5.

and the last video tonight, “For Loops”

The code:

and the result:

demosthenes131@rails-tutorial:~/workspace/TreeHouse $ ruby for_loop.rb
The current item is 1.
The current item is 2.
The current item is 3.
The current item is 4.
The current item is 5.
The current item is 6.
The current item is 7.
The current item is 8.
The current item is 9.
The current item is 10.
The current item is Programming.
The current item is is.
The current item is fun.

Challenge Task 1 of 1

Use a for loop to print each item in the animals array to the screen using the puts method.

and done!

And I am finished for tonight!