Days 84 to 92: Continuing with the Ruby on Rails tutorial… and some CSS!

So, my apologies on the slow updating here. I am still alive and moving forward. A couple of life events slowing me down, the usual being work, allergies and a horrible toothache but I am still working on my career change. A quick update on the progress:

  1. I completed a few CSS courses at Treehouse. I am rusty on it and wanted to get an update. I finished these:

Getting Started with CSS Badge


Basic Selectors badge

I will continue with this as I want a pretty solid front-end foundation despite my aim being back-end.

2. I finished chapters 5 and 6 in Michael Hartl’s Ruby on Rails tutorial. I am over halfway finished with it. I will be starting projects at that point!

Days 76 through 83: Catching Up on Posting But I’ve Been Studying!

Sorry to go missing from here, but I’ve remained busy. Allergies and such have been wreaking havoc on me, but I have continued studying Ruby on Rails Tutorial through Michael Hartl. I am currently halfway through Chapter 5 and I am learning a lot and really enjoying it.

I also just had my first interview through SparkHire. This was a unique experience. Its a one-way interview where you record your answers to questions. If I pass this part of the interview process I then move on to an in-person interview. Very exciting. I will be switching gears for a bit to brush up on my CSS skills at Treehouse.

Days 73, 74 and 75: Beginning (Again!) the Hartl Ruby on Rails Tutorial

So, a quick update and a proposed project. First, I have been slowed down over the last few days due to a severe sinus infection. I hate allergies! Nyquil knocked me out yesterday. About to do so again. Gotta get through this to keep working, both my day job and this.

I also finished up a first, small, project. It is using jQuery to display the top 50 games ranked according to Hotness at Board Game Geek. Take a look here to see it in action. I got help from the great folks at CodeNewbie Slack channel to iron out some bugs.

In any case, I have started back on the Michael Hartl Ruby on Rails tutorial. As of today I have completed chapter 1 and 2 again. I wanted to start from scratch to catch back up to where I need to be. I also have an idea for a 2016 US Presidential election web app I want to develop using the Twitter API. This will be my next project. I will be using JavaScript and Ruby on Rails to complete it. Stay tuned! Now, off to sleep!

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

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 13: Finishing Chapter 4 (Finally!)

I’m back at it and more determined than ever. I actually find myself looking forward to my studying.

By the way, I am trying out a new plugin for code syntax highlighting: Crayon Syntax Highlighter

Let’s start where I left off, with 4.4.3: Modifying built-in classes. So, before we took the properties of the String class adn gave them to our new class (not unlike the bite of a radioactive spider.)

Now we are going to look at how to call .palindrome? by modifying the String class to allow .palindrome? as a method!

See here that it doesn’t allow it right now:

So, let’s add the method to the class String:

This code defines the method “.palindrome?” by using something I think I neglected to explain at the end of last night. This line here:

As best I understand, self will refer to the object inside the class. So, we are asking whether the self is equal to itself in reverse.

Also, this feature of Ruby that allows us to add methods to built-in classes is powerful but with great power comes great responsibility. Also, this feature was used by Rails to add the .blank method to Ruby. The .blank method is useful to prevent variables from being blank, such as a user’s name or such. See how it works here:

This example shows us that “” is blank, but so is ” ” even though it is empty. Nil is also blank.

Next, we will discuss a controller class. We discussed classes before when we looked at the Static Pages controller. Remember:

So, with our knowledge from the previous lessons we can now appreciate this:

The StaticPagesController inherits from the ApplicationsController! It also has methods such as home, help and about which we see were defined:

We can also create a controller explicitly using the .new method, and then examine its class hierarchy. Take a look:

We can also call the controller actions, but they return nil since they are blank:

Now we are at the last stop on our tour of Ruby: the user class.

So, this time instead of entering the class definitions in the console as we have been doing all lesson, we will be creating a file in the application root directory called: examples_user.rb

Since there is a lot here, we will go through it line by line.

So this creates attribute accessors that correspond to a user’s name and email address. It creates “getter” and “setter” methods allowing us to retrieve (get) and assign (set) @name and @email instance variables. These always begin with an @ sign and are nil when undefined.

So, the .initialize method is the metod called when is executed. This .initialize method takes the attributes argument. Below that, two instance variables are defined and the attributes given above are pulled out.

Finally, a formatted_email method is defined using the values of the assigned @name and @email variables to build a formatted version of the user’s email address using string interpolation. Since @name and @email are instance variables, they are automatically available in the formatted_email method. Now, let’s load it in the console!

So, a couple of conventions new to me. The ‘.’ is Unix for “current directory” and telling Ruby ‘./example_user’ tells it to look or that file in that location. The code following creates an empty example user, fills in the name and email address to the corresponding attributes and then formats them pretty with the .formatted_email method!

And then we need to delete the example_user.rb file we made since we won’t need it anymore:

and then commit the other changes to the main source code repository, push to Bitbucket and deploy to Heroku.

Oh my. I completed Chapter 4!

So, tomorrow I will be going to my first Ruby on Rails Meetup with B’More on Rails. I will write about the experience afterwards.

Day 12: Continuing through Chapter 4

I am back at it.

So, I left off at 4.3 Other Data Structures. This part starts out talking about arrays and ranges. An array is just a list of elements in a particular order.

As you can see, the “split” method divides this string along the whitespace. This is the default method. You can split on nearly anything however. Notice we split along “x” here:

Below, we will set “a” as an array, and then can ask it what various elements in the array are. As is the convention in most computer languages, Ruby arrays are zero-offset, meaning the first element is 0, not 1.

As seen above, Ruby accesses arrays using bracket notation. You can also use synonyms for commonly accessed elements:

We can also use the “==” operator to do a comparison, the below asking whether the last element is also the -1 element.

We can also demonstrate that like a string, an array responds to the “length” method. Also, you can use other operators to compare in Ruby, such as the “!=” which is “not equal.”

You can also use other methods within Ruby on the array. You can ask whether it is “empty” use the method “.empty?”

Ask whether it “includes” a certain element using “.include?” and putting the element you seek in parentheses.

You can also sort it, reverse it, and shuffle it!

Notice that despite it being reversed and shuffled, the array remains the original pattern. To have Ruby keep the order when sorting you add a “bang” at the end, like so:

We can also add elements to the array using “push” as well as “<<"

You can also chain together the adding of elements, like so: >> a << "foo" << "bar" => [8, 17, 42, 6, 7, “foo”, “bar”]

This also demonstrates that you can add strings into the array. Using the method “.join” you can put these together.

As well join them together with commas.

This is because the array was not saved in the “.join” state.

Not, let’s look at ranges. These are similar to arrays. You can understand the difference when a range is converted to an array:

What happened here is, like the method “.to_s” to convert an element to a string, we attampted to use “.to_a” to convert the range to an array. Unfortunately, Ruby didn’t understand it. We need to use parentheses to define the range, like so:

Ranges are useful for pulling out array elements. Below, we will use %w to make a string array. I like this because I am lazy and who really wants to put quotation marks around all those strings?

And you can use the range to pull out array elements:

You can also use the “-1” index at an end of a range to select all the elements from your starting point to the end without having to use the array’s length:

You can also use a range with characters, like so:

Now it is time to move on to blocks. Mr. hartl explains that the block is “one of Ruby’s most powerful and most confusing features.” Let’s take a look, and I will try to get my head wrapped around it:

Alright, so the first line shows us putting the range 1..5 into an array. Now, after this we take this range and call the “.each” method on it. It is then passed to the block which is this:

The vertical bars, I’ve also heard them called pipes around the “i” are Ruby syntax for a block variable. So, if I understand correctly, it takes each element in the range, which is “1, 2, 3, 4, and 5” and multiplies each by 2. It can also be expressed another way:

The “do” and “end” way of doing this is best for a multi-line block, like so:

You can also use any variable name:

Let’s look at a few more, first with the “times” method:

Here, the 3.times passes through the block, summoning Beetlejuice.

Next, we will look at a block and use the “map” method. The first takes the range, (1..5) and applies the “.map” method. It passes it to the block, { |i| i**2 } where it is squared by 2. The “**” is how Ruby notates “power.”

This took me a bit to understand and I had to go and compare it to how each outputs. The .map method maps the results into an array, as best as I can figure out. Here are a few more examples, this time using characters:

Now, I am going to stop for a second because I want to be sure I understand the difference between .map and .each. Let’s take a look at a test I just did:

It appears to me that the .map method actually applies the block on to the elements in the array. It appears the .each just passes them on without it being applied. See here:

This makes me curious. I’m going back a bit and trying the .map on the earlier blocks we tried…

I am confused but this is also very interesting. The first is the original block example in the tutorial. Notice that at the main end it outputs the original range we called. The second one is with the .map method. At the end it outputs an array of nils (If I had a band this would be my band name.)

I did end up seeking help for this, however, in the CodeNewbie Slack Channel. Practicing Ruby explained it like this:

You can think of map as just being the same as the long form “create an array, call each on another array, operate on each element, append the result to the new array”

Time for hashes and symbols!

This is an empty hash. The use of those curly brackets should not confuse you. It is not a block! The tutorial says that “Hashes are essentially arrays that aren’t limited to integer indices.”

** I am going to start using comments to talk about certain lines like the tutorial does. Probably a better way anyway! **

So, the above defines each key and value one at a time. We can also use a hashrocket to do this! This is a hashrocket: =>

According to the tutorial, it is much more common for symbols to be used as has keys then strings. A symbol is prefixed with a colon, like this :name

Mr. Hartl describes the symbol as having less baggage than a string. See this:

but try it with a symbol:

and we get an error. Same with trying to reverse.

Also, stick with normal characters, letters and numbers. Ruby don’t like it:

So let’s try some symbols with our hashes!

>> user = { :first_name => “Atticus”, :last_name => “O’Sullivan” }
=> {:first_name=>”Atticus”, :last_name=>”O’Sullivan”}

There is also a new syntax that can be used in Ruby versions as of 1.9 that takes away the hashrockets but still defines the values to symbols as keys, like so:

Hash values can be anything, including other hashes. Hashes of hashes are nested hashes. Here is an example:

Hashes will also respond to the .each method

>> flash = { success: “It worked!”, danger: “It failed.” }
=> {:success=>”It worked!”, :danger=>”It failed.”}
>> flash.each do |key, value|
?> puts “Key #{key.inspect} has value #{value.inspect}”
>> end
Key :success has value “It worked!”
Key :danger has value “It failed.”
=> {:success=>”It worked!”, :danger=>”It failed.”}

And, the above uses the method “.inspect” that returns a literal representation of the object its called on. The use of inspect to print an object is so common that there is a shortcut for it:

Its the p function!

So, at this point the tutorial is taking us back to look at the app/views/layouts/application.html.erb which i will put below:

So first, parentheses are optional in Ruby. These two are equivalent:

Second, the media argument, while looking like a hash but is missing curly braces. They are also optional in this context. This is a little worrisome, but also makes it look more natural.

Also, the use of the hashrocket is the older syntax. This is used because “‘data-turbolinks-track’ => true” uses hyphens which are invalid.

Yay, time to move on to 4.4 Ruby classes. First, we will look at Constructors.

So, above we see that using the method .class returns the class that s is, which is “String”

We can also use something called a named constructor, here being:“foobar”) that has the same effect as the literal constructor which is s = “foobar”

This also works with arrays:

There is no reason to do this for strings and arrays.

So, with a hash the takes a default value for the hash, which is the value for a nonexistent key. Also, when a method gets called on the class itself, such as the .new method, it is called a class method. A method called on an instance is called an instance method.

Next, let’s look at class inheritance. This is demonstrated here using the .superclass method:

So, with this crude diagram below you will notice that the superclass of STRING is OBJECT and the superclass of OBJECT is BASICOBJECT. This is true of all Ruby objects.

String –> Object –> BasicObject

So now we are going to make our own class with a palindrome? method that returns true if the word is the same forward and backwords!

and let’s give it a try:

So, as seen in the above the method .palindrome will check the string given and see if it is the same forward and backwards. There is, however, a way to do this having our new “Word” class inherit from “String.” The above is creating a class to create a method to then take a string as an argument. The below example shows the inheritance:

And see below that now the new class has inherited all of the methods from String

And we can use the .superclass method on the new class as well.

OK, as much as I wanted to finish Chapter 4 today, I can’t do it! There is a lot of material here, and I want to understand it all. Tomorrow I will be picking up where I left off, looking at 4.4.3 Modifying built-in classes. I am learning a lot and really enjoying myself!

Day 11 Part 3: Return of the Rails

OK, back from playing board games with my wife and eating a crab cake. The crab cake was good and I am convinced my wife cheats at board games.

Back to the tutorial. So, nil is an object. As such this can be done:

Where the method to_s mto convert “nil” into a string. You can also try to ask whether nil is empty:

Unfortunately that returns an error. You can, however, use message chaining to get the response desired:

You can also use Ruby to answer a seemingly philosophical inquiry:

So neither “foo” nor “” is nil. Only nil is nil. That is deep.

Earlier we had defined “x” as “foo.” The following statement can be used to evaluate whether the string “x” is empty:

This is an alternate way to use the “if” keyword. You can also use “unless” the same way:

Going back to “nil,” it is a special object. It is the only Ruby object that is false in a boolean context. Here is a demonstration by using the !! (bang bang) which negates an object twice, coercing it to its boolean value.

By the way, the last was not something in the tutorial. I thought I would try it. I had to look up the error. According to an answer on Stackoverflow, the warning is because a string literal will always be true. Interesting.

Next up is method definitions. We saw this back when we used it to make our first two apps. We can also do the “def” command in a console. Take a look as we define a function:

An interesting note in the tutorial is that the variable “str” could be replaced with any valid variable name. He used the_function_argument and it worked. I decided to try something else:

So, at this point Mr. Hartl says we are able to understand the entire full_title helper from earlier in the tutorial.

The one element left is the topmost one:

Modules are a way to package together related methods. The Ruby documentation says:

A Module is a collection of methods and constants.

OK, it is 1AM and as much as I want to continue and finish Chapter 4, I should sleep. It is taking me longer, but there is a lot of meat in this chapter. I will continue bright and early tomorrow with “4.3 Other data structures.”

Day 11, Part 2: Electric Boogaloo

OK, I’m back for a short session.

First, a picture of my dog, Ajax. This one is from my old house in Ohio. He enjoys sitting and looking out windows.


Let’s continue on with the elseif command. If you remember where we left off, we did this to demonstrate control flow:

We can add in “elsif” to add more than one clause, such as:

I will admit to getting confused at this until I realized I had to leave the console because of something I did and restart it. I forgot to assign “foobar” back to “s” and I got errors. I went back, assigned “foobar” and it worked!

We can get a little deeper into Boolean variables using && for “and,” || for “or,” and ! for “not.” Take a look here:

You can see the first statement was not printed out since it was false. The others were true and it printed these to the screen.

OK, I am taking off again and will return later. My goal is to finish Chapter 4 tonight.

Day 11: Continuing Chapter 4 of Ruby on Rails Tutorial

Continuing on, the next part of Chapter 4 will be using the Rails console. It can be accessed using the command:

** Note, I will be using >> for the console prompt.

First, is looking at comments. This is something touched on a few times already. In Ruby on Rails (I will call it RoR from now on to save time) you do a comment with a hashtag first, like so:

and this can be done in the console, too.

The thing to understand, however, is by using this the console will ignore everything after the #.

Next, the lesson looks at strings. Using ” ” marks, whatever you put inside is printed to the screen, so that:




What is cool, I think is that you can do math with these. The example in the tutorial is:

This is called “String concatenation.” You can also do something called “variable assignment” where you assign a variable a string, like so:

and then you can do this:

This is called “String interpolation.”
or even get fancier:

You can also do the math like above, but notice it just jams the name together. You then have to add a space in. The string interpolation works better.

Next, we move on to the “puts” command. Is it sad I flashed back to Silence of the Lambs? “It puts the lotion on its skin…” Anyways, moving on…

The “puts” command prints the content of the string, removing the ” ” marks and then returns “nil” back. Nil is a Ruby value for “nothing at all.” It looks like this:

There is also a “print” command, and I find it strange it also returns “nil” but it looks like this:

Why? No idea. If you type the command like this:

Then you get the “nil” on its own line. Come on Ruby, get your act together.

The tutorial then touches on a question I have actually had in the back of my mind since I started this: single quotes vs. double quotes, or ‘ vs ”

I have wondered if they were interchangeable. I guess they are not. I tried ths out when I got to this part:

I noticed specifically that last one where it took my single quote marks: ‘foo’ and made it “foo”

That to me is very interesting. Let’s look at the prinicple implied here, which is stated in the tutorial as, “There’s an important difference, though; Ruby won’t interpolate into single-quoted strings.” See this:

So, in this example you can see I assigned the first_name and last_name variables, and then I did the string interpolation using the double quote marks. It returned the expected result. I then did it using the single quote marks and returned a backslash # combo. I am still trying to get my head around the backslash lesson here from the tutorial. Look at this:

>> ‘\n’ # A literal ‘backslash n’ combination
=> “\\n”

\n is a newline command. When put inside the single quotes, it returns a double backslash and then the “n.” The tutorial states that: “As with the #{ combination in our previous example, Ruby needs to escape the backslash with an additional backslash; inside double-quoted strings, a literal backslash is represented with two backslashes.”

I feel like I am missing something here. Thankfully, I was able to ask about this at the Saturday Coding Slacker chat, and come to find out that the \ tells Ruby to pay attention to the special character following it. Single quotes are used for raw strings. Also, “Just use double quotes all the time, and you’ll be fine.” Hat tip to practicingruby for the help. I am saving his explanation here for my later benefit:

So… single quotes vs. double quotes.

Just use double quotes all the time, and you’ll be fine.

The thing about single quotes is that they’re meant to be used for raw strings, things that don’t have special control characters in them.

The advantages of using single quotes are mostly very very subtle, and irrelevant to most everyday coding

So… here’s the thing… backslash usually means “Whatever comes after this is a special character, so do something special with it”

In single quotes, you don’t have many special characters, but you still need a way to express single quotes inside of single quotes!

>> ‘For \’example\’, this string’
=> “For ‘example’, this string”

Without the slashes, Ruby wouldn’t know what to do, because you’d have this:

‘For ‘example’, this string’

Which to Ruby looks like two strings , not one, with an *example* method or variable jammed between them.

So.. that’s why you still need ‘\\’ instead of \

Because even though \ is pretty much useless in single quotes, it is necessary for escaping ‘, so now since \ has a special meaning, you need to be able to escape itself

The next part of the tutorial deals with objects and message passing. Everything in Ruby is an object. You can pass a message to an object like so:

In this example, the “.length” message inquires as to how many characters the string “foobar” is. Let’s look at another:

So, in this one I asked whether the string was empty using the message “.empty?” and found that “foobar” and ” ” where not empty, but that “” is empty. Isn’t it interesting that it recognized the space I made as not empty? Well, I think it’s interesting.

The question mark at the end is a Ruby convention that indicates the return value is boolean: true or false. This is good for control flow. Take a look at this:

So, you define s as “foobar” and then you ask Ruby to tell you whether it is empty, and give it a few strings to phrase the response. The result is “The string is nonempty.”

OK, I will return later. My Jack Russell, Ajax, needs picked up from the groomer!

Day 10: Working Through Chapter 4 of the Ruby on Rails Tutorial

I will be going back and typing up my reviewing of Chapter 2 and 3, but I want to get in the habit of reviewing the content on here. It really helped me to solidify what I was learning. I definitely suggest it to others!

So, Chapter 4 is titled Rails-flavored Ruby. Mr. hartl explains that, “This chapter is designed to give you a solid foundation in Rails-flavored Ruby, whether or not you have prior experience in the language.” I will be working on it tonight and tomorrow morning, so it will be split up on here. I want to absorb it, not just breeze through and not get it. Here we go!

The chapter starts out looking at the application.html.erb file in views/layouts. In particular, the focus is on this line:

The “stylesheet_link_tag” is a Rails function that works to include “application.css” for all media types. The first goal in this chapter is going to be to create a “helper” to allow for the base title, “Ruby on Rails Tutorial Sample App” to appear on the home page without the leading pipe symbol, the |. Not sure why we hate the | but down with the |.

To do this, we will be creating a helper called “full_title” that will return only the base title. The helper will be created in “app/helpers/application_helper.rb” and will look like this:

And then, we go to “app/views/layouts/application.html.erb” and switch this line:


and then go to “test/controllers/static_pages_controller_test.rb” and change the test for the Home page to say:

and go to the “app/views/static_pages/home.html.erb” file and remove the line:

Then, we run the Guard exec and see that we only have no failures.

Well, that is it for today. I had another long day of work and I am beat. I will be continuing in the morning, plus I plan to drop in to the Saturday Coding at CodeNewbie on Slack tomorrow. See details here. My goal for tomorrow is to complete Chapter 4 and maybe to do my review of Chapter 2. I am not sure yet if I should continue to do the reviews as thoroughly as I am or to push on quicker through the material. Any thoughts?