Skip to content

Instantly share code, notes, and snippets.

@stacietaylorcima
Last active January 10, 2018 03:06
Show Gist options
  • Save stacietaylorcima/d056d7fdde9a9303822c83a9431f6dc2 to your computer and use it in GitHub Desktop.
Save stacietaylorcima/d056d7fdde9a9303822c83a9431f6dc2 to your computer and use it in GitHub Desktop.
Includes basic language details, classes, and activity notes.

Ruby: Introduction

Objectives

  • Define the String, Symbol, and Integer data types in Ruby.
  • Understand how to use variables.
  • Demonstrate how to perform math operations using Ruby Arithmetic operators.
  • Understand how to define methods.
  • Understand how to pass arguments.
  • Understand how to return a value from a method.
  • Understand how to comment code.
  • Understand the best practices for writing expressions.
  • Rails is a web application framework built using the Ruby programming language in the same way that Angular is a framework built using JavaScript programming language

Practicing Ruby Basics:

Printing code to an output window:

  • puts command (actually a method) converts a value to a String and prints it to the console. There are some values that should not be converted to Strings though, so puts won't work for us all the time.
  • p prints the true value of an object, rather than a String-ified version of the object.

In Ruby, almost everything is an object. An object has attributes (characteristics) and methods (behaviors). Attributes are things the object knows about itself and methods are the things it can do.

Class: just think of a class (really, its objects) as something that lets you work with specific data in various ways.

Commenting Ruby Code: The pound sign indicates that everything after it in the same line is a comment. Comments are ignored by programs and are used to document the code. You can also use a =begin =end block to write a multiline comment.


Data Types

Integer

"Integer" is the class that Ruby uses to represent Integer values. It is the data type that defines the characteristics and behaviors of whole numbers. Ex: -1, 0, 1000

Math: You can do math with objects of the Integer class. Most operators you use in math will retain their meaning in Ruby.

1 - 1 # subtracts the integers and returns the result
1 * 5 # multiplies the integers and returns the result
10 / 2 # performs integer division and returns the result
10 % 5 # returns the remainder after performing division

Variable:

  • An expression is a chunk of Ruby code that always yields a value. The expression 1 + 1 is evaluated and Ruby returns the result. If we want to store that result we'll need to use a variable. In Ruby, variables do not need to be given a type when they are defined. We use the =operator to set the result of the expression to a variable.
  • Variables are like boxes that allow us to store information. We can perform an operation, like adding 1 to 5, and store that result in a variable. Now, every time you call that variable, it will give us the result without performing the operation again. They can also be reassigned at any time and will only keep the latest assigned value.
result = 5 + 1 # The result will store the result of evaluating the expression.

p result # will print out 6

Variable Naming Convention: If you need to use more than one word as the variable name, use an underscore to separate the words. Variable names must begin with a letter or an underscore. There are a few exceptions.

inspect Method: can be called on any object. It returns the contents or value of the object. Using p favorite_number returns the same result as doing puts favorite_number.inspect

rand Method: Ruby also gives us a way to generate random numbers using the Random class. We get a random number between two points by using a range passed into the rand method. A range specifies a start and end point between two numbers:

rand(1..100) # returns a random number between 1 and 100, inclusive (includes 100 as a possibility)
rand(1...100) # returns a random number between 1 and 100, exclusive (excludes 100 as a possibility)

String

"String" is the data type for words or phrases in Ruby and many other programming languages. Strings are delineated in Ruby using single or double quotation marks around words or other characters. Both "hello world" and 'hello world' are valid ways of writing a String.

Double Quotes & Single Quotes: Both are acceptable ways to write Strings.

  • If we want to use double quotes inside double quotes we could “escape” the inner quotes to avoid Ruby thinking that we are closing the String. A backslash before each character that we want to escape tells Ruby that "this next thing doesn't mean what you think it means." "I'm "full" but bring on dessert"

String Interpolation: You can evaluate a variable inside a String using word1 = "bacon"

p "I love #{word1}" # prints "I love bacon"

String Class Methods:

"I am a String".length # returns the number of characters in that String
"racecar".reverse # returns a reversed version of that String
"mike".capitalize # returns "Mike"
"argh".upcase # returns "ARGH"
"OUCH".downcase # returns "ouch"

Symbol

  • Symbols are like Strings but with less functionality. A Symbol is designated by inserting a colon (:) to the left of a word. Symbols can contain any alphanumeric character, but must start with a letter.
    • Computers process Symbols faster than Strings. We will use Symbols extensively with Ruby on Rails.
    • Here are a few examples:
p :hello
p :hi123
p :HELLO

TrueClass & FalseClass (Boolean)

  • TrueClass and FalseClass represent true and false respectively. Booleans can be used in conditional logic and can be return values in some expressions.

NilClass

  • There's a special object in Ruby named nil.
    • nil represents nothing.
    • nil is important in programming because it helps programmers to determine the validity of an operation.
    • nil is different from 0 or a blank String ("").
    • nil is an object in Ruby that represents nothing. We can prove that nil is an object by assigning it to a variable.

nil Example:

  • Square brackets ([]) are used in Ruby to reference locations. When we type "Bloc"[7] we instruct Ruby to return the 7th character in the "Bloc" String. This operation returned nil because there is no 7th character in the "Bloc" String.
  • Notice that "Bloc"[2] returned o. We instructed Ruby to return the 2nd character in the "Bloc" String, so why didn't Ruby return l? The reason is that counting starts at 0 in programming languages. "Bloc"[0] would return B.

Methods

  • A method is a way of describing a behavior in programs. Methods are like verbs and objects are like nouns. Think of a printer. One verb that can be used to describe the behavior of printing is print. The printer is our object (noun) and print is our method (verb).

Vocab:

  • Call: run or execute a method.
  • Define: compose or write a method.

Ruby Method Definition Structure:

def print_walking_dead_character(name)
  p "#{name} is a character in The Walking Dead"
end

The first three parts, def print_walking_dead_character(name), are known as the method heading or method signature.

  • the keyword def tells Ruby that we are about to define a method.
  • print_walking_dead_character is the name we are assigning our method. Method names are similar to the variable names we saw before as the method name help us to call what the method contains by using the method name.
  • name inside of a parenthesis is a parameter. Parameters are placeholders like variables for arguments that we can pass to the method when we call it. The method will then be able to use these values in the execution of instructions. We can allow multiple parameters by separating each parameter with a comma. We can also define a method with no parameters.
    • Parameters are for method definitions and arguments are for method calls. the instructions of the method will print to the screen the result of interpolating the name into the String.
  • tell Ruby the method definition is complete by using the keyword end.

Implied Parentheses:

  • Ruby syntax allows for "implied parentheses", meaning that the Ruby interpreter will assume that method argument means method(argument). Remember how we said that p is really just a Ruby method? This means that when you call p "Something", you're really calling p("Something").

Default Parameter Values:

  • We can give our parameters a default value, and if we call the methods with no arguments, the default values will be used instead.
def greet_people(name = "human")
  p "Hello, #{name}"
end

return Methods: can use the keyword return to return a value explicitly.

  • However, Ruby can use an “implicit return” since, by default, a method in Ruby returns the last thing it evaluates.
  • Nothing below the return statement will be executed.
def work_out
  return "not today"
  p "I'm getting my fitness on!"
end

@stacietaylorcima
Copy link
Author

Assignments

Integer Practice:

Challenge:
Define a method called subtract with a parameter called num1 and another parameter called num2. The method will return the result of subtracting num2 fromnum1. Here's how the method would be called and the expected return:

subtract(11, 7) #=> 4
subtract(7, 11) #=> -4

Solution:

def subtract(num1, num2)
  num1 - num2
end

Challenge:
Define a method called multiply with a parameter called num1 and another parameter called num2. The method will return the product of both arguments passed into the method. Here's how the method would be called and the expected return:

multiply(5, 2) #=> 10
multiply(10, 0) #=> 0

Solution:

def multiply(num1, num2)
  num1 * num2
end


String Practice:

Notes:

Changing Case of Strings in Ruby

"hello James!".downcase    #=> "hello james!"
"hello James!".upcase      #=> "HELLO JAMES!"
"hello James!".capitalize  #=> "Hello james!"
"hello James!".titleize    #=> "Hello James!"

Challenge:
Define a method called to_batman_comic with a parameter called text. The method will return an up-cased version of the word and add an exclamation point at the end. Here's how the method would be called and the expected return:

to_batman_comic('bam') #=> 'BAM!'
to_batman_comic('zoink') #=> 'ZOINK!'

Solution:

def to_batman_comic(text)
  text.upcase + "!"
end

Notes:

  • Ruby comparison operators like >= return boolean values naturally. You don't need to use a conditional, and you almost never want to return string equivalents of true and false. Also, Ruby convention is to use a question mark in the name of methods that return boolean values. -stackoverflow

Challenge:
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise. Here's how the method would be called and the expected return:

first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true

Solution:

def first_longer_than_second(first, second)
  first.length >= second.length
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment