Ruby basics Flashcards
How do you declare a class name?
When naming your classes you will use CamelCase formatting. CamelCase uses no spaces and capitalizes every word.
# Class naming class MyFirstClass end
class MySecondClass end
What do you use when the entire expression fits on one line in a do/end block?
Use { }
What does namespace mean and do
he :: symbol is used to define a namespace, which is just a way to group classes in Ruby and differentiate from other classes with the same name. For example ActiveRecord::Base is referring to the Base class in the ActiveRecord module, to differentiate from other classes also named Base.
However, when looking at the method list on the side bar, the :: means something different: it means that the method after the :: is a class method
What are methods denoted by :: in documentation
class methods
What are methods denoted by # in documentation
instance methods
How do we express nothing in programming
By using the value nil
How do you check if something has a nil value?
.nil?
How is nil treated in an if statement?
Treated as FALSE, as it represents an absence of content
What does => nil mean when your run puts “test”
It means that you have no return
a = puts “test”
puts a
What will be printed on the screen?
nil
What are variables
Variables are used to store information to be referenced and manipulated in a computer program.
They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.
It is helpful to think of variables as containers that hold information.
Their sole purpose is to label and store data in memory. This data can then be used throughout your program.
Variable scope
Inner scope can access variables initialized in an outer scope, but not vice versa.
What’s the distinguishing factor for deciding whether code is a block?
arr = [1, 2, 3]
for i in arr do
a = 5 # a is initialized here
end
puts a # is it accessible here?
the key distinguishing factor for deciding whether code delimited by {} or do/end is considered a block (and thereby creates a new scope for variables), is seeing if the {} or do/end immediately follows a method invocation
Is for do..end creating an inner scope? Why is that useful?
No
Variable created in the for will be accessible outside of it as it will be in the same scope.
How many types of variables are there?
5
Constants Global variables Class variables Instance variables Local variables
Constant variables
Created with uppercased letters
Cannot be declared in a method’s definition
Can be changed in ruby, while in other languages not. Still, dont change them once declared
Global variables
created with $
are accessible everywhere in the app, overriding all scope boundaries
there can be complications when using them
Class variables
declared with @@ accessible by instances of my class and the class itself
Use when you need to create a variable related to the class and when instances of that class do not need their own value for that variable
Must be initialized at the class level
Instance variables
Declared with @
Available in the instance of the parent class
Why are parameters used in a method
Parameters are used when you have data outside of a method definition’s scope, but you need access to it within the method definition. If the method definition does not need access to any outside data, you do not need to define any parameters.
Default parameters
def say(words=’hello’)
Optional parentheses
For example, say() could be rewritten as just say. With arguments, instead of say(“hi”), it could just be say “hi”.
Method definition and local variable scope
A method definition creates its own scope outside the regular flow of execution. This is why local variables within a method definition cannot be referenced from outside of the method definition. It’s also the reason why local variables within a method definition cannot access data outside of the method definition (unless the data is passed in as a parameter).
Mutating caller methods
Methods that perform actions on the argument passed to a method which mutates the caller
a = [1, 2, 3]
Example of a method definition that modifies its argument permanently
def mutate(array)
array.pop
end
p “Before mutate method: #{a}”
mutate(a)
p “After mutate method: #{a}”
Pop mutates the caller
What is a conditional
a fork in the road.
our data approaches a conditional and the conditional then tells the data where to go based on some defined parameters.
How are conditionals formed?
Conditionals are formed using a combination of if statements and comparison operators (, <=, >=, ==, !=, &&, ||).
What’s the order of precedence?
Used when deciding how to evaluate multiple expressions. The following is a list of operations from highest order of precedence (top) to lowest (bottom).
<=, , >= - Comparison
==, != - Equality
&& - Logical AND
|| - Logical OR
Describe a case statement
Has similar functionality to an if statement but with a slightly different interface.
Case statements use the reserved words case, when, else, and end.
How do you loop?
loop do //something end
How do you skip the rest of the code in a loop and start with the next iteration?
By using next
How do you exit the loop immediately?
By using break
What is a while loop
A while loop is given a parameter that evaluates to a boolean (remember, that’s just true or false). Once that boolean expression becomes false, the while loop is not executed again, and the program continues after the while loop.
How to write a while loop
while boolean statement
do something
end
How to write an until loop
until boolean statement
do something
end
What’s an until loop
Opposite of while loop
What are the ways to use a do/while loop
loop do do something if this condition is true break out of loop end
begin
do something
end while condition
Difference between do while and while loops
Code in do while gets executed at least once
What are for loops used for?
for loops are used to loop over a collection of elements
What’s the difference between for loops and while loops
Unlike a while loop where if we’re not careful we can cause an infinite loop, for loops have a definite end since it’s looping over a finite number of elements
How do you write a for loop?
It begins with the for reserved word, followed by a variable, then the in reserved word, and then a collection of elements.
for i in 1..10 do
puts i
end
What is a range?
A range is a special type in Ruby that captures a range of elements. For example 1..3 is a range that captures the integers 1, 2, and 3.
What does a for loop return?
The collection of elements after it executes
What does a while loop return
nil
What method is used to decide if a number is not event?
odd?
What are iterators?
Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection.
What does each do?
loops through each elements of a collection and allows you to operate over each element
Explain how .each works
The block’s starting and ending points are defined by the curly braces {}. Each time we iterate over the array, we need to assign the value of the element to a variable. In this example we have named the variable name and placed it in between two pipes |. After that, we write the logic that we want to use to operate on the variable, which represents the current array element. In this case it is simply printing to the screen using puts.
What’s a block?
Lines of code ready to be executed, inside { } or a do..end
When do you use do…end
When performing multi-line operations
What is recursion
Another way to create a loop.
Recursion is the act of calling a method from within itself..
What does each_with_index do?
Iterates through a collection and makes available the index and the item for use
What does .pop do to an array?
removes last element in an array, and mutates the caller
What does “mutate the caller” mean?
permanently changes the caller
What is the caller?
the collection calling an instance method
What does push do?
adds an item to the end of an array
Shovel operator
«_space;- adds item to end of array
mutates the caller
Map method
The map method iterates over an array applying a block to each element of the array and returns a new array with those results.
What’s the other name you can use for map?
collect
Do map or collect mutate the caller?
These methods are not destructive (i.e., they don’t mutate the caller).
How do you know which methods mutate the caller or not?
You have to use the methods and pay attention to the output in irb; that is, you have to memorize or know through using it.
Why would you use delete_at
Delete a value at a certain index
How would you delete a value at a certain index?
delete_at
What does delete do
Deletes all instances of a provided value in an array
How do you delete all instances of a value in an array
Use .delete(value)
What does uniq do?
Deletes all duplicates in an array , returning the results as a new array. It does not modify the initial array
How can you make the uniq method forcibly mutate the caller?
Use !
Are uniq and uniq! the same methods?
No, they are different methods, one returns a new array while the other mutates the caller
How do you filter an array in Ruby
use the select {bloc}
What does .select do?
This method iterates over an array and returns a new array that includes any items that return true to the expression provided.
Does .select mutate the caller?
It does not, it returns an array with the filtered elements
! exception
Not all methods are destructive/ mutates the caller. Check the documentation.
Example of methods which are destructive but don’t have !
push / pop
What does unshift do?
Adds the value provided to the front of the array.
It is the opposite of .pop
What does to_s do to an array?
creates the string representation of the array
What does include? do?
The include? method checks to see if the argument given is included in the array.
What does the ? at the end of a method mean?
usually means that it will return a boolean value
What does flatten do?
The flatten method can be used to take an array that contains nested arrays and create a one-dimensional array.
It does not mutate the caller, it is not destructive
How do you create an one-dimensional array?
Use flatten
What does each_index do?
The each_index method iterates through the array much like the each method, however the variable represents the index number as opposed to the value at each index.
What does each_with_index do?
each_with_index gives us the ability to manipulate both the value and the index by passing in two parameters to the block of code. The first is the value and the second is the index
What does the .sort method do?
Sorts the array
Is sort method destructive?
Check the array
What does .product do?
It returns an array that is a combination of all elements from all arrays.
What’s the difference between each and map?
each provides a simple way of iterating over a collection in Ruby and is more preferred to using the for loop. The each method works on objects that allow for iteration and is commonly used along with a block. If given a block, each runs the code in the block once for each element in the collection and returns the collection it was invoked on. If no block is given, it returns an Enumerator
map also works on objects that allow for iteration. Like each, when given a block it invokes the given block once for each element in the collection. Where it really differs from each is the returned value. map creates and returns a new array containing the values returned by the block.
What does each return?
the caller
What does map return?
creates and returns an array with the modified values
How does map work?
map also works on objects that allow for iteration. Like each, when given a block it invokes the given block once for each element in the collection. Where it really differs from each is the returned value. map creates and returns a new array containing the values returned by the block.
How does each work?
each provides a simple way of iterating over a collection in Ruby and is more preferred to using the for loop. The each method works on objects that allow for iteration and is commonly used along with a block. If given a block, each runs the code in the block once for each element in the collection and returns the collection it was invoked on. If no block is given, it returns an Enumerator
What does puts return?
nil
What does map return if not block is given?
Enumerator
What do you use each for?
Iterating through a collection
What do you use map for?
Transforming a collection
What is a hash
Data structure that stores items by associated keys
What is the difference between a hash and an array
A hash stores item by associated keys, while an array stores them by index
How are entries in a hash referred to?
Key-value pairs
How is a hash created
Using symbols as key and data types as values
All key-value pairs in a hash are surrounded by { }, and separated by ,
How do you create a hash?
The older syntax comes with a => sign to separate the key and the value.
old_syntax_hash = {:name => ‘bob’}
The newer syntax is introduced in Ruby version 1.9 and is much simpler. As you can see, the result is the same.
new_hash = {name: ‘bob’}
How do you add to an existing hash?
person[:hair] = ‘brown’
How do you remove something from a hash?
person.delete(:age)
How do you retrieve a piece of info from a hash?
person[:weight]
How do you merge 2 hashes?
person.merge!(new_hash)
Why do you use the ! in the merge of 2 hashes?
This modifies the caller, instead of returning a separate merged array. It makes the modification on the spot
How do you iterate over hashes?
Use the each method and assign a variable to both the key and the value of the hash
person = {name: ‘bob’, height: ‘6 ft’, weight: ‘160 lbs’, hair: ‘brown’}
person.each do |key, value|
puts “Bob’s #{key} is #{value}”
end
Hashes as optional parameters
You can pass an empty hash as a default value to an parameter in a method.
You can use a hash to accept optional parameters when you are creating methods
def greeting(name, options = {}) if options.empty? puts "Hi, my name is #{name}" else puts "Hi, my name is #{name} and I'm #{options[:age]}" + " years old and I live in #{options[:city]}." end end
greeting(“Bob”)
greeting(“Bob”, {age: 62, city: “New York City”})
What does .empty? do?
Detect whether a variable has anything passed into it
What is the peculiarity of a hash in a def
if it is the last argument, the { } are not required when calling the method
What to choose between an array and a hash?
When deciding whether to use a hash or an array, ask yourself a few questions:
Does this data need to be associated with a specific label? If yes, use a hash. If the data doesn’t have a natural label, then typically an array will work fine.
Does order matter? If yes, then use an array. As of Ruby 1.9, hashes also maintain order, but usually ordered items are stored in an array.
Do I need a “stack” or a “queue” structure? Arrays are good at mimicking simple “first-in-first-out” queues, or “last-in-first-out” stacks.
What datatypes can you use as keys in a hash?
Those that are hashable, such as String, Int, Double etc
What does has_key? do?
The has_key? method allows you to check if a hash contains a specific key. It returns a boolean value.
What does select do in a hash?
The select method allows you to pass a block and will return any key-value pairs that evaluate to true when ran through the block.
What does fetch do in a hash?
The fetch method allows you to pass a given key and it will return the value for that key if it exists.
You can also specify an optional return if the key is not present
What does to_a do in a hash?
The to_a method returns an array version of your hash when called.
my_hash = {age: 12, name: “John”}
p my_hash.to_a.first.last
puts my_hash
p my_hash.to_a
How do you retrieve all the keys only?
.keys
How do you retrieve all the values only?
.values
Create a file
File.new(“name”,”w+”)
.new method with 2 arguments (a name and the access on file)
When should you close a file
When the opening doesnt happen in a block
Why should you close files?
They continue occupying space in memory otherwise
What does r do when opening a file?
read-only (starts at beginning of file)
What does w do?
write-only (if the file exists, overwrites everything in the file)
What does w+ do?
read and write (if the file exists, overwrites everything in the file)
What does a+ do?
read-write (if file exists, starts at end of file. Otherwise creates a new file). Suitable for updating files.
Open a file for reading
File.read(“file_name”) - Spits out entire contents of the file.
What does File.readlines(“file_name”) do?
Reads the entire file based on individual lines and returns those lines in an array.
Open file for writing
File.open(“name”,”w”) { | file | file.write(“new text”) }
Use write or puts to write to a file
What should you do after this?
sample = File.open(“name”,”w+”)
sample.puts(“another text”)
sample.close
you need to close the file if the operation of writing happens outside a block
What’s the other option for writing to a file
File.open(“filename”,”w+”) do | file |
file_name «_space;“text”
end
Delete a file
File.delete(“name”)
What does the Pathname class do?
he Pathname class exposes pretty much all of the methods of File and Dir. The advantage to using Pathname is you can declare an instance of it and access the class methods of File and Dir on the instance object.
What’s the Dir class?
Dir - Dir shares some of File’s methods. However, it is not an IO stream.
What is REGEX
Regex stands for regular expression. A regular expression is a sequence of characters that form pattern matching rules, and is then applied to a string to look for matches.
How do you create a regex
Creating regular expressions starts with the forward slash character (/). Inside two forward slashes you can place any characters you would like to match with the string.
/ /
What is =~ used for
We can use the =~ operator to see if we have a match in our regular expression. Let’s say we are looking for the letter “b” in a string “powerball”. Here’s how we’d implement this using the =~ operator
irb :001 > “powerball” =~ /b/
=> 5
What is the result of =~ useful for
We can use it as a boolean to check for matches.
def has_a_b?(string) if string =~ /b/ puts "We have a match!" else puts "No match here." end end
has_a_b?(“basketball”)
Match method
Same as =~
What does match return?
This method returns a MatchData object that describes the match or nil if there is no match.
What is the result of match useful for?
You can use a MatchData object to act as a boolean value in your program:
def has_a_b?(string) if /b/.match(string) puts "We have a match!" else puts "No match here." end end
has_a_b?(“basketball”)
What are Ruby Standard Classes?
When you have a specific action that you need to perform, look for it first among Ruby’s standard classes.
Example of Ruby Standard Classes?
Ruby’s Math module has a method called sqrt that you can use right away.
Math.sqrt(400) //20
Math::PI
=> 3.141592653589793
You can use Ruby's built-in Time class. irb :003 > t = Time.new(2008, 7, 4) => 2008-07-04 00:00:00 -0400 irb :004 > t.monday? => false irb :005 > t.friday? => true
Variables as pointers?
Variables act as pointers to a place in memory
What happens when you change the value of a variable?
When you change the value of a variable you re-assign it to a different physical place in memory. This is what = does.
What happens when you assign the initial value back to a variable?
If you re-assign the initial value back, you are actually occupying a different space in memory, not the initial one
What happens if you assign the same value to a different variable?
If you assign the variable to a different variable, you will have to different spaces in memory holding the same value
a = "hi there" b = a a = "not here"
Here, you are potingin to different spaces in memory for different values,
But if at the end you do a = “hi there” you will potin to 2 different places but have the same value in both
Can you pass Blocks in methods as parameters?
Yes, as the last parameter
passing_block.rb
def take_block(&block)
block.call
end
take_block do
puts “Block being called in the method!”
end
The only difference is that when you call the take_block method you pass it a bloc via do…end
What does the & in a method definition means?
Tells us that the argument is a block.
You put it in front of the argument in the definition
How do you tell a method that the argument passed to it is a block?
&
What are we doing here and what is the result?
def take_block(number, &block)
block.call(number)
end
number = 42
take_block(number) do |num|
puts “Block being called in the method! #{num}”
end
Here we are passing the number into the take_block method and using it in our block.call.
Define the take_block method which takes 2 parameters, a number and a block.
The block is called in the definition with the number being passed as a parameter. If you do not call the method with the number parameter the method will not work
What are procs?
Procs are blocks that are wrapped in a proc object and stored in a variable to be passed around
How do you define a proc?
proc_example.rb
talk = Proc.new do
puts “I am talking.”
end
talk.call
Can procs take arguments? How?
Yes
proc_example.rb
talk = Proc.new do |name|
puts “I am talking to #{name}”
end
talk.call “Bob”
Can procs be passed into methods? How?
passing_proc.rb
Yes
def take_proc(proc) [1, 2, 3, 4, 5].each do |number| proc.call number end end
proc = Proc.new do |number|
puts “#{number}. Proc being called in the method!”
end
take_proc(proc)
What is exception handling?
Exception handling is a specific process that deals with errors in a manageable and predictable way
Why is exception handling needed?
When your programs are interacting with the real world, there is a large amount of unpredictablility. If a user enters bad information or a file-manipulating process gets corrupted, your program needs to know what to do when it runs into these exceptional conditions.
One common occurrence of this is when a nil value makes its way into our program.
What’s the format of the exception handling and the reserved words
exception_example.rb
begin # perform some dangerous operation rescue # do this if operation fails # for example, log the error end
How does the exception work?
When an exception, or error, is raised, the rescue block will execute and then the program will continue to run as it normally would. If we didn’t have the rescue block there, our program would stop once it hit the exception and we would lose the rest of our print-out.
How else can you use the rescue word?
You can also use the rescue reserved word in-line like so:
inline_exception_example.rb
zero = 0
puts “Before each call”
zero.each { |element| puts element } rescue puts “Can’t do that!”
puts “After each call”
What’s the result of the following code and why?
zero = 0
puts “Before each call”
zero.each { |element| puts element } rescue puts “Can’t do that!”
puts “After each call”
Before each call
Can’t do that!
After each call
It does so because it isn’t possible to call the each method on an Integer which is the value of the zero variable. If we remove the rescue block, the second puts method will not execute because the program will exit when it runs into the error. You can see why the word “rescue” is relevant here. We are effectively rescuing our program from coming to a grinding halt. If we give this same code the proper variable, our rescue block never gets executed.
Can we save pre-existing errors?
Yes
divide.rb
def divide(number, divisor)
begin
answer = number / divisor
rescue ZeroDivisionError => e
puts e.message
end
end
puts divide(16, 4) puts divide(4, 0) puts divide(14, 7)
Here we are rescuing the ZeroDivisionError and saving it into a variable e. We then have access to the message method that the ZeroDivisionError object has available.
What’s ZeroDivisionError?
Pre-existing Ruby error
What do we say when something goes wrong?
An exception has been raised
Ruby built in exceptions examples:
StandardError TypeError ArgumentError NoMethodError RuntimeError SystemCallError ZeroDivisionError RegexpError IOError EOFError ThreadError ScriptError SyntaxError LoadError NotImplementedError SecurityError
Stacks and methods
When ruby invokes a method, the method is added to Ruby’s ‘stack’.
The stack trace first tells us where the error occurred and why.
What’s the stack trace for the error in this code?
1 def greet(person) 2 puts "Hello, " + person 3 end 4 5 greet("John") 6 greet(1)
Error:
greeting.rb:2:in +': no implicit conversion of Fixnum into String (TypeError) from greeting.rb:2:in
greet’
from greeting.rb:6:in `’
Stack trace:
The stack trace first tells us where the error occurred and why: line 2 of greeting.rb, and the error was because the types don’t match. The error occured due to the call made in the ‘main’ context on line 6, which contains the line that called the method with incorrect arguments, line 2.
What’s the stack trace of this?
def space_out_letters(person) return person.split("").join(" ") end
def greet(person) return "H e l l o, " + space_out_letters(person) end
def decorate_greeting(person)
puts “” + greet(person) + “”
end
decorate_greeting(“John”)
decorate_greeting(1)
main -> decorate_greeting -> greet -> space_out_letters (passes result back) -> greet -> decorate_greeting -> main
Error:
H e l l o, J o h n
greeting.rb:2:in space_out_letters': undefined method
split’ for 1:Fixnum (NoMethodError)
from greeting.rb:6:in greet' from greeting.rb:10:in
decorate_greeting’
from greeting.rb:14:in `’
Initialize a git repository command
git init
How do you add a remote repository as a remote of existing local repo
git add remote origin “link goes here”
List all remote repositories
git remote
Rename a remote repository
git remote rename old_name new_name
What does origin mean when used to work with remote repositories?
It’s an alias for the remote repo to use locally and interact with the remote repo
What’s in git/config?
The .git/config file is where all the configuration settings for your local repository are held, and overrides any global settings.
Set the upstream branch - what’s the message you receive that confirms this?
git push -u origin master
That -u flag sets the upstream repo, which causes our local master branch to track the master branch on the remote repo which is aliased as origin.
You will also see a message saying that you have set up your local master branch to track the remote master branch, thanks to the -u flag.
What’s the benefit of an upstream branch?
Can use git push afterward to push the the remote repo
Scenarios for using pull request?
Sometimes the code in your remote repository will contain commits you do not have in your local repository. In those situations, you will need to pull the commits from the remote repository into your local repository. There are four basic scenarios when you will run into this:
- You work on a team, and multiple people pushed code to the remote repository.
- You pushed to the remote repository from a different machine.
- Your project is public on GitHub and somebody contributed to it.
- You made a change to a file directly on GitHub.com.
What does fetch do?
Will download the commit data for each branch that the remote repo contains.
Because we are currently working with our local master branch, the git fetch command will fetch the commits from the remote repo containing the tracked remote branch.
git fetch
What does git diff do?
git diff master origin/master
This command tells git to compare the local master branch to the master branch on the remote repo which is aliased origin. Put another way, we’re comparing the commits in our local repository with the commits in the remote repository.
You can compare other branches
What does pull do?
Pulls changes into local repo
git pull
Since the local master branch has been configured to track the origin/master branch, you do not have to specify what branch to pull from.
Could have used git pull origin master
The local repo is identical to the remote repo now
What does clone do?
Pull down contents of existing remote repo into a new local repo, and add a remote to the local repo pointing to remote repo.
git clone
When to use clone?
git clone is used mainly when you need to work with a remote repository, and do not yet have a local repository created. For example, if you just joined a new project, the first thing you’d likely do is git clone the project in order to start working on it locally.
Another common use case is if you want to pull down an open source project. For example, if you wanted to check out the source code for the popular open source web development framework, Ruby on Rails, you can issue this command:
git clone https://github.com/rails/rails.git
What happens if you don’t specify the second parameter in the clone command?
If you don’t specify a directory name then the default behavior is that a new directory will be created with the same name as the cloned repo.
Nest git repositories
Not allowed.
You are allowed to create another folder in a git repository, but not another git repository
Why are parameters useful in a method
When you have data outside the method, but you want to use it inside the method
What’s a method invocation?
Another name for calling a method
What do we pass to a method when we call it?
arguments
What are arguments
pieces of information which are passed to a method invocation to be modified or used to return a specific result
Case statements and variables
You can save the result of a case statement to a variable
a = 5
answer = case a when 5 "a is 5" when 6 "a is 6" else "a is neither 5, nor 6" end
puts answer
Case arguments
You dont need to give the case an argument, but you have to do a comparison in each when
a = 5
answer = case when a == 5 "a is 5" when a == 6 "a is 6" else "a is neither 5, nor 6" end
puts answer
Ruby evaluating true/false expressions
In Ruby, every expression evaluates to true when used in flow control, except for false and nil
a = 5 if a puts "how can this be true?" else puts "it is not true" end
Difference between do/while and loop
the code in loop gets executed at least once until the condition is hit