Learn ruby the hard way: the hard way!

I set myself a challenge: learn programming every day, except weekends, for at least 5 hours. The reason behind this, was me beeing distracted by timeconsuming stuff like gaming, youtube and social media. I really want to prove to myself, that I can push through it and learn the stuff as soon as possible.

Let’s continue with the second half of the book: Learn Ruby the Hard Way

 

 

Memorizing Logic

 

The truth tables:

 

table.1 “Ruby the Hard Way”

NOT true?
!false true
!true false
OR (||) true?
true || false true
true || true true
false || true true
false || false false
AND (&&) true?
true && false false
true && true true
false && true false
false && false false
NOT OR true?
not (true || false) false
not (true || true) false
not (false || true) false
not (false || false) true
NOT AND true?
!(true && false) true
!(true && true) false
!(false && true) true
!(false && false) true
!= true?
1 != 0 true
1 != 1 false
0 != 1 true
0 != 0 false
== true?
1 == 0 false
1 == 1 true
0 == 1 false
0 == 0 true

 

and the truth terms:

 

  • && (and)
  • || (or)
  • ! (not)
  • != (not equal)
  • == (equal)
  • >= (greater-than-equal)
  • <= (less-than-equal)
  • true
  • false

 

Boolean Practice

 

true && true  => true

false && true  => false

1 == 1 && 2 == 1 => false

“test” == “test” => true

1 == 1 || 2 != 1 => true

true && 1 == 1 => true

false && 0 != 0 => true

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) => true

!(“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

 

This was kinda easy, im going to show how i solved it by going through the last statement:

  1. from inner bracket first => “testing” == “testing” OR “Ruby” == “Fun” => true
  2. but !( makes a true statement wrong and vice versa, so => false
  3. 3 THE SAME AS 3 AND false => false

What If

 

people = 20
cats = 30
dogs = 15

if people < cats    # true, so the code runs

    puts “Too many cats! The world is doomed”

end

if people > cats

    puts “Not many cats! The world is saved!”

end

if people < dogs

    puts “The world is drooled on!”

end

if people > dogs  # true, so the code runs

    puts “The world is dry!”

end

 

dogs += 5   #dogs = dogs + 5 = 20

 

if people >= dogs   # true, so the code runs

    puts “People are greater than or equal to dogs”

end

if people <= dogs  # true, so the code runs

   puts “People are less than or equal to dogs!”

end

if people == dogs   # true, so the code runs

   puts “People are dogs.”

end

 

Else and if

 

people = 30
cars = 40
trucks = 1

 

if cars > people

    puts “We should take the cars.” #this will be printed

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.” #this will be printed

else

    puts “We still cant decide”

end

 

if people > trucks

    puts “Alright, lets just take the trucks.” #this will be printed

else

    puts “Fine, lets stay home then”

end

 

Elsif statements

  1. If the first statement isn’t true, it will be skipped.
  2. If it’s true it ignores all the code that’s written under the codeblock.
  3. Checks the elsif statement, if its true it runs.
  4. If the If and all elsif statments are false, the else codeblock runs.

 

 

Making decisions, If statements inside if statements

 

puts “You enter a dark room with two doors. Do you go through door #1 or door #2?”

print “> ”

door = $stdin.gets.chomp    #waits for the user input and assigns it to a variable(door)

if door == “1”

puts “There’s a giant bear here eating a cheese cake. What do you do?”

puts “1. Take the cake.”

puts “2. Scream at the bar.”

print “> ”

bear = $stdin.gets.chomp   #waits for a user input again and assigns it to a variable(bear)

 

if bear == “1”

puts “The bear eats your face off. Good job!”

elsif bear == “2”

puts “The bear eats your legs off. Good job!”

else

puts “Well, doing %s is probably better. Bear runs away.”   #if you choose to type in other                                                                                                                           than 1 and 2, you trigger the                                                                                                                              else branch

end

 

elsif door == “2”

puts “You stare into the endless abyss at Cthulu’s retina.”

puts “1. Blueberries.”

puts “2. Yellow jacket clothespins.”

puts “3. Understanding revolvers yelling melodies.”

 

print “> ”

insanity = $stdin.gets.chomp

 

if insanity == “1” || insanity == “2”

puts “Your body survives powered by a mind of jello. Good job!”

else

puts “The insanity rots your eyes into a pool of muck. Good job!”

end

else

puts “You stumble around and fall on a knife and die. Good job!”

end

 

So basically you can have multiple if statements inside if statements with their own blocks of code. The same principle applies to them aswell.

 

 

Loops and Arrays

 

For the next exercise I’m going to use for-loops and arrays.

Arrays:

in this example, are containers that store the stuff that results out of for-loops.

[] opened/closed brackets indicate the start/end of an array.

 

 For-Loop:

a loop that goes through each thing in an array of things.

 

 

the_count = [1,2,3,4,5]
fruits = [‘apples’, ‘oranges’,’pears’,’apricots’]
change = [1, ‘pennies’, 2, ‘dimes’, 3 , ‘quarters’]   #arrays can be mixed up with integers                                                                                                         and strings

# this first kind of for-loop goes through a list

# in a more traditional style found in other languages

for number in the_count

puts “This is count #{number}”

end

# same as above, but in a more Ruby style

# this and the next are the preferred

# way Ruby for-loops are written

fruits.each do |fruit|

puts “A fruit of type: #{fruit}”

end

# also we can go through mixed lists too

#note this is yet another style, exactly like above

# but a different syntax ( way to write it )

change.each {|i| puts “I got #{i}”}

# we can also build lists, first start with an empty one

elements = []

# then use the range operator to do 0 to 5 counts

# the range operator “..” tells the loop to consider every number from and starting with 0 until and 5 included

(0..5).each do |i|

puts “adding #{i} to the list.”

# pushes the i variable on the *end* of the list

elements.push(i)

end

# now we can print them out too

elements.each {|i| puts “Element was: #{i}”}

 

rewriting the traditional style into Ruby style:

the_count.each do |number|

puts “this is count #{number}”

end

 

Why is a for-loop able to use a variable that isn’t defined yet?

“The variable is defined by the for-loop when it starts, initializing it to the current element of the loop iteration, each time through.”

 

 

 

While Loops

 

A While-Loop:

Runs the block of code as long as the statement of the boolean expression is true.

 

i = 0
numbers = []    #opens the array for us to store the integers we get later from the loop

 

while i < 6    #as long as i is less than 6 run the code block …

puts “At the top i is #{i}”   #i = 0

numbers.push(i)   #pushes the number to the empty array

 

i += 1   #adds i+1 so, the first time the code gets run 0+1 = 1 then 1+1, 2+1 , etc…

puts “Numbers now: “, numbers   #prints all the numbers in order, that are present in the                                                                          array at the time the code is run 

puts “At the bottom i is #{i}”

end

 

puts “The numbers: ”   #after the loop has ended is shows all the integers in the array

 

Converting the while-loop to a function:

def loop(number)
i = 0
numbers = []
while i < number
puts “At the top i is #{i}”
numbers.push(i)

i += 1

      puts “Numbers now: “, numbers

      puts “At the bottom i is #{i}”

  end

end

loop(2)   #calling the function with an argument

loop(6)

 

 

Accessing Elements of Arrays

 

to access something out of an array like:

animals = [ bear, tiger, snake, snail ]

bear = animals(0)

 

programmers start counting from 0, so if we want to take the 3rd animal out of the array we type:

snail = animals(3)

 

animals = [ bear, tiger, snake, snail ]

   >                       0,        1,         2,         3

 

 

Branches and Functions

def gold_room
 puts "This room is full of gold. How much do you take?"

 print "> "
 choice = $stdin.gets.chomp

 #this line has a bug so fix it ? 
 if choice.include?("0") || choice.include?("1")  #if number 0 OR 1 ,
 how_much = choice.to_i                           convert it to string
 else
 dead("Man, learn to type a number")    #if input is not an integer 
 end

 if how_much < 50   #if input LESS THAN 50 puts...
 puts "Nice, you're not greedy, you win!"
 exit(0)   #exit, just exits the game
 else
 dead("You greedy bastard!")   #if number higher than 50 run dead function
 end
end

def bear_room
 puts "There is a bear here."
 puts "The bear has a bunch of honey."
 puts "The fat bear is in front of another door."
 puts "How are you going to move the bear?"
 bear_moved = false    #inital state of variable value is false

 while true   #if state of bear_moved changed to true, print...
 print "> "
 choice = $stdin.gets.chomp

 if choice == "take honey"
 dead("The bear looks at you then slaps your face off.")
 elsif choice == "taunt bear" && !bear_moved    #if choice is taunt bear AND not 
 puts "The bear has moved from the door. You can go through it now." false puts..
 bear_moved = true
 elsif choice == "taunt bear" && bear_moved
 dead("The bear gets pissed off and chews your legs off")
 elsif choice == "open door" && bear_moved
 gold_room
 else
 puts "I got no idea what that means."
 end
 end
end

def cthulhu_room
 puts "Here you see the great evil Cthulhu."
 puts "He, it, whatever stares at you and you go insane."
 puts "Do you flee for your life or eat your head?"

 print "> "
 choice = $stdin.gets.chomp

 if choice.include? "flee"   #if answer includes string "flee go to start function
 start
 elsif choice.include? "head"
 dead("Well that was tasty!")
 else
 cthulhu_room    #else send to cthulhu_room function
 end
end

def dead(why)   #this function puts what's in other functions and adds "Good job!"
 puts why, "Good job!"
 exit(0)
end

def start 
 puts "You are in a dark room."
 puts "There is a door to your right and left."
 puts "Which one do you take?"

 print "> "
 choice = $stdin.gets.chomp

 if choice == "left"
 bear_room   #sends to bear_room function
 elsif choice == "right"
 cthulhu_room   #sends to cthulhu_room function
 else
 dead("You stumble around the room until you starve.")
 end
end

start       #runs the start function

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s