Ruby | Conditionals and Flow Control

Answering Odin Project questions on Ruby Conditionals and Flow Control:

    • What is a “boolean”?
      A boolean is a binary variable that holds two possible values “true” and “false”
    • What are “truthy” values?
      Objects that are considered true in a boolean are truthy, false are considered falsey. What’s true and false varies across different languages.
    • Are nil, 0, "0", "", 1, [], {} and -1 considered true or false?
      nil -> false, 0->true, “0”->true, “”->true, 1->true, []->true, {}->true, -1->true
    • When do you use elsif?
      When you have more than two parts in an if statement.
    • When do you use unless?
      When you want to test for ‘false’.
    • What does <=> do?
      This ‘spaceship’ operator returns 1, 0, or -1 instead of 1, 0
      For example: a <=> b
      If a < b, return -1.
      If a = b, return 0.
      If a > b, return 1.2 <=> 5, returns -1 because 2 is less than 5.
    • Why might you define your own <=> method?
      When you are sorting an array. You can use it for both integers and strings. Strings are sorted according to the ASCII order and so is case sensitive. Uppercase letters come before lowercase letters.
    • What do || and && and ! do?
      || = logical ‘or’
      Evaluates the first operand. If true, returns true. Otherwise, returns the value of the second operand.

      && = logical ‘and’
      Evaluates the first operand. If false, returns false. Otherwise, returns the value of the second operand

      ! = ‘not’
      If the expression is true, returns false. If the expression is false, returns true.

    • What is returned by puts("woah") || true?
      true
    • What is ||=?
      a ||= b would mean if ‘a’ is false, then set it equal to ‘b’. Otherwise, leave it the same value before running the conditional.
    • What is the ternary operator?
      ? :
      boolean_expression ? true_expression : false_expression
      Returns the true_expression if boolean_expression is true. Otherwise, returns false_expression.
    • When should you use a case statement?
      You should use a case statement when you want to match a value to a manageable number of conditions.

||= explanation: http://ruby.zigzo.com/2013/02/01/wat-double-pipes-equals-in-ruby/
Spaceship Operator: http://www.evc-cit.info/cit020/beginning-programming/chp_07/custom_sort.html
Follow their Web Development course here: http://www.theodinproject.com/ruby-programming/advanced-ruby-building-blocks?ref=lnav

Advertisements

Ruby on Rails Resources

Ruby:

https://www.ruby-lang.org/en/news/2013/12/25/ruby-2-1-0-is-released/

Rails:

http://guides.rubyonrails.org/4_0_release_notes.html

Rails Installation Guide:

http://railsinstaller.org/en
http://guides.railsgirls.com/install/
http://installfest.railsbridge.org/installfest/ I used this one to install on my Windows OS because I attended a RailsBridge event. I found it easy to follow. 

Ruby Gems:

https://rubygems.org/

Bundler:

http://bundler.io/
Bundler provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed.

Learn Ruby:

TryRubyhttp://tryruby.org/levels/1/challenges/0 Really fun way to get introduced to the language. Great layout&design and user friendly.
Ruby on Codecademy: https://www.codecademy.com/tracks/ruby Very well written and easy to follow.
Ruby Programming on Odin: http://www.theodinproject.com/ruby-programming
Ruby Monk: http://rubymonk.com/learning/books/1-ruby-primer
Ruby the hard way: http://learnrubythehardway.org/book/ It really is hard. Especially if you don’t have a programming background.
Ruby in 100 minutes: http://tutorials.jumpstartlab.com/projects/ruby_in_100_minutes.html
Chris Pinehttps://pine.fm/LearnToProgram/chap_01.html
Master Ruby blockshttp://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes
Bastards book of Rubyhttp://ruby.bastardsbook.com/toc/
Ruby Newbie Odin Gisthttps://gist.github.com/brianllamar/11261930

Learn Rails:

Rails for Zombies: http://railsforzombies.org/ Really excellent lessons. Read more here.
Tech Talent South Rails Beginner Lesson:
http://techtalentsouth.slides.com/techtalentsouth/zero-to-heroku-workshop?token=r_LQ9_iu#/
Michael Hartl’s Tutorial: https://www.railstutorial.org/book/beginning
Ruby on Rails on Odin: http://www.theodinproject.com/ruby-on-rails

Ruby Help

http://ruby-doc.org/
https://www.codecademy.com/glossary/ruby/

Blogs:

http://www.jamesfend.com/learned-ruby-rails-12-weeks-launch-freelancify
http://www.codenewbie.org/blogs/ruby-roundup-1
http://www.smashingmagazine.com/2009/03/getting-started-with-ruby-on-rails/

Atlanta Ruby Users Group:

http://www.atlrug.com/

Jobs:

https://toprubyjobs.com/
https://www.jrdevjobs.com/jobs

Ruby Regular Expression Editor:

http://www.rubular.com/

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/

How to add your solution to a project on Odin

If you are doing the lessons on The Odin Project, then you’ll know that they have several projects for each lesson you do. They offer a really cool option to add your solution to their website. If you are confused as to how to do it, below is a link as well as instructions:

Watch how here: https://www.youtube.com/watch?v=V74l_zS1x8E

1. Scroll to the bottom of the Odin Project page and find this icon. Click on it to get the link to the exact Github file where you can add your solution:

2. Click the link corresponding to what you want to do. There is one for fixing errors and one for adding your solution. If you are adding a solution, click the first link:

github repo odin

3. You will be taken to their Github page where the lesson is located. Click the edit button and scroll to find the project you are adding your solution to:

4. Add your name and your Github link where it says to:

Odin Edit Github

5. Then scroll the Github page to the bottom to write a note under Propose File Change. Click the green Propose File Change button when you are finished.

propose file change github

6. You will be taken to a pull request page and will need to click the Create Pull Request green button.

pull request github

7. Confirm your title and comment. Then click the green Create Pull Request button at the bottom of the text fields.

create pull request github

8. You will be taken to a page that looks something like the below image. Now you just have to wait for The Odin Project to add your name onto the website!

pull request screenshot

9. Added!
solution odin project

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.