JavaScript String Manipulation Challenge

Going through Udacity‘s free online JavaScript course, I came across this challenge:

Your Challenge

If given a string of a two word name formatted with any mix of capitalization, can you manipulate the string to ensure the first name has a capital first letter and the last name is totally capitalized? Assume there’s a space between the names. For instance, turning a string like "cAmEROn PittMAN" into "Cameron PITTMAN". Your answer should be a single string saved to the variable called finalName.

Take a look at MDN’s documentation on string methods for clues, then try it yourself!

==============================================

My solution:

Unnamed QQ Screenshot20151001081020

The breakdown:

Line 1: var name = "AlbERt EINstEiN";

A variable called name has the value AlbErt EINstEiN. All lines in JS have to end with a semicolon so that the system knows it is the end of a line.

Line 3: function nameChanger(oldName) {

A function called nameChanger will take in an argument called oldName. All functions will start with a curly brace after the function name.

Line 4: var finalName = oldName;

A variable called finalName has the value of oldName.

Line 6:  var nameArray = oldName.split(' ');

The value of oldName is taken and a .split() method is called to make a string array from oldName. The array values are created using a ‘ ‘ (space) as the separator. For example, if
oldName = "AlbERt EINstEiN";
oldName.split(' ');
would equal have the values: [AlbERt', 'EINstEiN']

Then these values would be saved in a new variable called nameArray.

Line 7: var lastName = nameArray[1].toUpperCase();

The second value (since arrays start with 0, nameArray[1] would be the second value) in nameArray is changed to all uppercase letters. This is stored in a new variable called lastName. For example, if
nameArray = ['AlbERt', 'EINstEiN']
nameArray[0] = ['AlbERt']
nameArray[1] = ['EINstEiN']
nameArray[1].toUpperCase();
would be equal to ['EINSTEIN']
var lastName = ['EINSTEIN']

Line 8: var firstName = nameArray[0].toLowerCase().split('');

The first value in nameArray is changed to all lowercase letters. Then the letters will be separated from each other since the .split(”) is an empty string. So if
nameArray[0] = ['AlbERt'],
firstName = ['a', 'l', 'b', 'e', 'r', 't'];

Line 9: var firstLetter = firstName.splice(1).join('');

firstName will start the array from the second value (1) and then the array will be joined together to form one string. For example:
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName.splice(1) = ['l', 'b', 'e', 'r', 't'];
firstLetter = ['l', 'b', 'e', 'r', 't'].join('') = ['lbert'];

.splice() method
.join() method

Line 10: var firstNameJoin = firstName[0].toUpperCase() + firstLetter;

The first value in the array firstName is changed to uppercase, then added to the value of firstLetter.
firstName = ['a', 'l', 'b', 'e', 'r', 't'];
firstName[0] = ['a'];
firstName[0].toUpperCase() = ['A']
firstNameJoin = ['A'] + ['lbert'] = ['Albert'];

Line 12: finalName = firstNameJoin + ' ' + lastName;

finalName = [‘Albert’] + [‘ ‘] + [‘EINSTEIN’] = [‘Albert EINSTEIN’];

Line 14: return finalName;

Saves the value of finalName.

Line 18: console.log(nameChanger(name));

'console.log' will show on the screen whatever is in the parentheses. Inside the parentheses, the function we made, nameChanger, is called with a parameter inserted called ‘name‘. ‘name‘ is the name of the variable that was defined in the beginning on Line 1.

There are many other ways to find a workable solution, so don’t think you HAVE to do it this way.

Rails for Zombies | Code School

I just completed the Rails for Zombies by Codeschool. It’s a FANTASTIC way to learn how Rails 4 works. The professor Gregg Pollack is great at explaining the code and how models are connected to controllers to views. The course Rails for Zombies Redux is free, includes 5 lessons, and follows the following structure: video lesson, 4-5 exercises to practice what you learn, wrap-up video.

There’s exercises after every video lesson that let you practice what Gregg explains in the video so you can apply what you learned. I highly recommend watching the video lessons more than once and have a pen and paper in hand (or whatever you use to take notes) to write down his clear explanations.

Here are some screenshots:

ruby for zombies

rails for zombies

rails for zombies codeschool

After completing the course, you can add a completion badge to your LinkedIn profile. I highly recommend this course to anyone learning Rails, and especially for before tackling the Hartl tutorial.

Sandi Metz

Sandi Metz(http://www.sandimetz.com/) at the Atlanta RailsConf 2015 talking about object-oriented design: https://youtu.be/OMPfEXIlTVE

Looks at Ruby code, how to simplify and reduce the amount of code you write.

Sandi Metz wrote a book called Practical Object-Oriented Design in Ruby.
A description of what the book is all about and how it’s changed the way people learn to code:

Practical Object-Oriented Design in Ruby (POODR) is a programmers tale about how to write object-oriented code. It explains object-oriented design (OOD) using realistic, understandable examples.   POODR is a practical, readable introduction to how OOD can lower your costs and improve your applications.

POODR will help you:

  • Decide what belongs in a single class
  • Avoid entangling objects that should be kept separate
  • Define flexible interfaces among objects
  • Reduce programming overhead costs with duck typing
  • Successfully apply inheritance
  • Build objects via composition
  • Design cost-effective tests
  • Craft simple, straightforward, understandable code

If your code is killing you and the joy is gone, POODR has the cure.

Read more or purchase here: http://www.sandimetz.com/products/

Cash Register lesson in Codecademy

While completing the Cash Register (step 3/7) exercise on Codecademy’s JavaScript course, I came across this answer from tony de araujo that helped me understand how the code I was writing was executed.

alt text

On line 29 we call the scan method from object cashRegister and pass in an item called “eggs”

“eggs” gets inserted into the function via the input parameter item which is an interface.

For this function call instance, “eggs” becomes the value of variable item.

The switch switches the case “eggs” to true, which triggers the function add on line 4 and the value of 0.98 is added to variable total on line 2.

In truth, the program only starts executing at line 29. All the stuff above line 29 is preliminary data that JavaScript will use once it starts running the program. What I mean is that JavaScript scans the program once and it makes an inventory of what is supposed to do. Then, it starts running at line 29 and downward.

Source: https://www.codecademy.com/forum_questions/54b129f79113cbb05a0035e4

Free Code Camp

A friend recommended a new free coding resource for learning full-stack development called Free Code Camp. I’ve been trying out their lessons the past two days to see how they are. I’m very impressed with their community, network, organization, and support. They don’t teach Ruby and Ruby on Rails, which is what I’ve been learning the past few months. Instead they focus more on JavaScript and Node.js.

This is what their curriculum looks like:

800 Hours of Practice:

    800 Hours of  Real World Work Experience:

  • 100-hour Nonprofit Project
  • 200-hour Nonprofit Project #1
  • 200-hour Nonprofit Project #2
  • 300-hour Nonprofit Project

I really love the idea that you can work on some real-world non-profit projects after you complete their lessons. It’s great to get real experience and add a project to your portfolio. I don’t know any other free or paid coding school that gives you such a great opportunity.

Their HTML and CSS portion was fairly easy to go through and it was a great review since I had learned it earlier in the year. Their jQuery and JavaScript lessons use Codecademy, so you will still need to go between the two websites. I’m currently going through the Free Code Camp JavaScript so we’ll see how their subsequent lessons fair.

Free Code Camp is also on LinkedIn as an education institute and they encourage you to add them to your LinkedIn profile. Also check out Free Code Camp on Github. They are also on Facebook. I joined the Atlanta chapter.

Github for Beginners

If you’re learning coding/programming and haven’t already, you must sign up for a Github account to showcase your work.

Some resources for learning Github:

http://jlord.us/git-it/challenges/get_git.html
I did these series of challenges twice. The first time I was completely lost, as it was my first time using the command line on my Windows computer. The second time around, I was able to fully understand every step.

http://rogerdudler.github.io/git-guide/
This website is really simple and straightforward. Write down each of the steps listed in this guide to know what order you have to do git commands.

http://readwrite.com/2013/09/30/understanding-github-a-journey-for-beginners-part-1
This is a great article that breaks down everything about Github and explains the who, what, when, where, why, and how.

Integrating Bootstrap with Rails 4

Today’s project was incorporating Bootstrap into my Rails application.

To start, I redid this basic Ruby on Rails tutorial on Tech Talent South’s website. To make it more personal, I decided to make a list of movies instead of a list of random members. I followed this guide by Koren Leslie Cohen on how to change column names in a database. It’s a great, simple guide, but I found that when I changed  the :name and :age into :title and :release, respectively, they didn’t change across all my views so I still had to go in manually and change them, which to me, beats the purpose of using the rails g migration command. Not sure if there is a better way to do it, as I am still new to Rails, but will keep searching.

To incorporate Bootstrap, I downloaded Bootstrap and followed along with the Readme file included in the download package.

This is what I added to my Gemfile:

gem 'sprockets-rails', '>=3.0.0.beta1'
gem 'sass-rails', '>=5.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3.1'

In the guide, they recommended to add these two gems for SASS:
gem ‘bootstrap-sass’, ‘~> 3.3.4’
gem ‘sass-rails’, ‘>= 3.2’

But I kept getting errors when running ‘bundle install’ so I’m thinking these two gems are outdated. Could be because I had downloaded Bootstrap a couple months ago and my version of Bootstrap is older. So I had to go in and manually change the versions. This is where I found the latest version number for sass-rails.

If you come across the following error:

Bundler could not find compatible versions for gem "sprockets-rails"

Then you can go here to double check and see if your version of ‘sprockets-rails’ is compatible with your version of Ruby and Rails.

This is a great step-by-step guide on how to integrate Bootstrap 3.3 with Rails 4.2. After step 7, you can pick and choose what code you want to integrate into your site. Also refer to the CSS page on the Bootstrap home.

This is my final product: https://tts-sunsplat.c9.io/members (still a work in progress!)

Need to:
1. Add errors if no text in form fields.
2. Add movie descriptions to the ‘view’ page. (Maybe API?)
3. Add color.
4. Add images.

Ruby |Breaking down the Caesar Cipher

Caesar Cipher in Ruby

From Wikipedia:

In cryptography, a Caesar cipher, also known as Caesar’s cipher, the shift cipher, Caesar’s code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.

There’s a brief video about it from Harvard’s CS50 class.

Breaking down the following solution line by line:

1  puts "Word please: "
2  text = gets.chomp.downcase
3
4  puts "Number please: "
5  n = gets.chomp.to_i
6
7  def caesar_cipher(text, n)
8    alphabet = ('a'..'z').to_a 
9    key = Hash[alphabet.zip(alphabet.rotate(n))]
10   text.each_char.inject("") { |newtext, char| newtext + key[char] }
11 end
12
13 puts caesar_cipher(text, n)

Line 1:

  puts "Word please: "

Prompts the user to write a word.

Line 2:

  text = gets.chomp.downcase

gets takes the word the user writes and .chomp cuts off the end parameters (like “/n”). The new word is now referred to as ‘text’.

Line 4:

  puts "Number please: "

Prompts the user to write a number.

Line 5:

  n = gets.chomp.to_i

gets takes the input number (which is a string)

.chomp cuts the end parameters off, and then .to_i turns the number into an integer.

The new number is now referred to as ‘n’.

Line 7:

  def caesar_cipher(text, n)

def caesar_cipher(text, n) defines a new method called caesar_cipher that takes in two arguments text and n which are taken from Line 2 and Line 4 respectively.

Line 8:

  alphabet = ('a'..'z').to_a

Defines a new variable called alphabet that is equal to individual letters a all the way to z. These letters are each their own individual string. The .to_a turns the 26 letters into an array. This array is named alphabet.

Line 9:

  key = Hash[alphabet.zip(alphabet.rotate(n))]

A new variable key is defined. It is equal to Hash[alphabet.zip(alphabet.rotate(n))]

Let’s break it down.

alphabet.rotate(n) – What does this do?
.rotate is a method in Ruby that returns a new array by rotating the array elements.

For example:

       a = [ "a", "b", "c", "d" ]
       a.rotate #=> ["b", "c", "d", "a"]
       a #=> ["a", "b", "c", "d"]
       a.rotate(2) #=> ["c", "d", "a", "b"]
       a.rotate(-3) #=> ["b", "c", "d", "a"]

In this case, alphabet.rotate(n) takes the alphabet variable (the array of all 26 letters) and rotates the array n number of times. The n comes from what the user puts when prompted in the beginning (see Line 5).

alphabet.rotate(n) is inside alphabet.zip(). What does alphabet.zip() do?

.zip is a useful method for combining collections in an ordered way.

       [1,2,3].zip(['a', 'b', 'c'])
       #=> [[1, "a"], [2, "b"], [3, "c"]]

As you can see, the above two arrays are combined together so that each number is paired with each letter. The number 1 is associated with ‘a’ and so forth.

.zip can also take 2 (or more) arguments to zip into the first:

       ['a', 'b', 'c'].zip( [1,2,3], ['oogie', 'boogie', 'booger'] )
       #=> [["a", 1, "oogie"], ["b", 2, "boogie"], ["c", 3, "booger"]]

So going back to our code, alphabet.zip(alphabet.rotate(n)) is taking our rotated alphabet variable array and matching the new order with our original alphabet array. For example, if n was 2, our alphabet variable would match with the new rotated alphabet like so:

  n = 2
  alphabet = ['a', 'b', 'c', 'd', 'e'..'z']
  new_alphabet = ['c', 'd', 'e', 'f', 'g'..'b']  // new_alphabet = alphabet.rotate(2)
  alphabet.zip(new_alphabet) = ['a', 'c'],['b', 'd'], ['c', 'e'] ..['z', 'b']

Hash[alphabet.zip(alphabet.rotate(n))]
Hash turns each pairing into key => value pairings.

For example, alphabet.zip(new_alphabet) would be equal to [['a' => 'c'], ['b' => 'd'], ['c' => 'e']..['z' => 'b']]. So now the value for ‘a’ is ‘c’, and so on.

Line 10:

Let’s break down this, too:

  text.each_char.inject("") { |newtext, char| newtext + key[char] }

What exactly is this line of code doing??

  text

text takes the string entered by the user (See Line 2).

  text.each_char

each_char takes the string entered by the user (text) and separates the string into their separate characters. For example, if text were “apple”, each_char would make “apple” turn into “a”, “p”, “p”, “l”, “e”.

  text.each_char.inject("")

.inject("") sends each character through the block (the block being everything between the brackets {}).  Each character of text passes through the block in the argument place labeled char.

The ("") defines the default starting point. It means the first time we pass through the block, we are defaulting (starting) with an empty string (“”).

  { |newtext, char| newtext + key[char] }

This is a block. It is connected to the .inject enumerator method, which just means every time you use .inject, you will have a block following it. There are two arguments in this block ‘newtext‘ and ‘char‘ that are new.

newtext is the default (starting) string, which in the first go through, would be an empty string (“”) because that’s what we declared after the .inject method: text.each_char.inject("")

char is the individual characters from the text variable.

key[char] takes in the individual character [char] and assigns its value found from the key variable we defined in Line 9.

All the individual characters will be run through the block until there are no more characters in the text string. To see how this works, let’s use the example of “apple”.

     text.each_char.inject("") { |newtext, char| newtext + key[char] }

     text = "apple"
     n = "2"

     first run through => 
     "apple".each_char = "a", "p", "p", "l", "e"
     ("a", "p", "p", "l", "e").inject("") { |"", "a"| "" + key["a"] }
     key["a"] == "c"
1st  ("a", "p", "p", "l", "e").inject("") { |"", "a"| "" + "c" }
2nd  ("p", "p", "l", "e").inject("c") { |"c", "p"| "c" + [key["p"]=="r"] }
3rd  ("p", "l", "e").inject("r") { |"r", "p"| "cr" + "r" }
4th  ("l", "e").inject("r") { |"r", "l"| "crr" + "n" }
5th  ("e").inject("n") { |"n", "e"| "crrn" + "g" }

     "crrng"

Line 11:

  end

end is connected to our method caesar_cipher and means that we are done defining the method.

Line 13:

  puts caesar_cipher(text, n)

This writes the result of the caesar_cipher method for us.

Project located here: http://www.theodinproject.com/ruby-programming/building-blocks?ref=lnav


Rotate method: http://apidock.com/ruby/Array/rotate
Method arguments: http://www.skorks.com/2009/08/method-arguments-in-ruby/
Zip method: http://dfriedm.github.io/blog/2013/10/12/ruby-zip-method/
Hash: http://ruby-doc.org/core-1.9.3/Hash.html
Each_char: http://ruby-doc.org/core-2.1.0/String.html#method-i-each_char
Inject: http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-inject
https://blog.udemy.com/ruby-inject/

Codermanual – Part V finished

I’ve just finished Part V of Codermanual, the JavaScript & jQuery section. It was an oversimplification of the language, I feel, but the way it was explained, really helped me wrap my head around how programming languages work. The amount of information in this part was overwhelming, but I feel confident now that I can handle JavaScript.

I had tried to learn JavaScript on my own back in April but I was using Codecademy at that time and I think their JavaScript tutorial was way too advanced. Everything went over my head. It was my first time learning an object-oriented programming language. Around the same time, I kept hearing a lot about Ruby and Ruby on Rails so I tried Codecademy’s Ruby course instead and found it much easier to grasp so I stuck with it and am now working on Michael Hartl’s Ruby on Rails tutorial.

I’m halfway through and realizing that there are still many things about Ruby that I have questions about, so I’m going to pause Hartl’s tutorial as well as Codermanual and do The Odin Project’s Ruby Programming course (which is also free!).

The more I learn, the more I realize how little I know.