Use LEFT and RIGHT arrow keys to navigate between flashcards;
Use UP and DOWN arrow keys to flip the card;
H to show hint;
A reads text to speech;
257 Cards in this Set
- Front
- Back
For nerd points, answer any of the following:
Who created Ruby? Where (in what country) was Ruby created? When?
|
Who? Matz (Yukihiro Matsumoto) Where? Japan When? The 90s (specifically, 1994) |
|
What does REPL stand for?
And what does a REPL do? |
Read, Evaluate, Print, Loop
A REPL takes user input (read), evaluates it (eval), returns a result to the user (print), then asks for another input (loop). |
|
Ruby variables assign names to pieces of data. A variable's name can consist of which types of characters? |
Letters, numbers or underscores.
Ruby variables must also be lowercase and have no spaces. They cannot start with a number and cannot include special characters like $, @ or &. Best practice is to use snakecase. Examples: count, first_lesson, students_in_class |
|
Assign the number 5 to the variable x. |
x = 5 |
|
What are the two basic types of numbers in Ruby? |
Integers (Fixnum) and decimals (Floats). |
|
What are surrounded by quotes and used to store collections of letters and numbers? |
Strings.
FYI, the shortest possible string is called the empty string: "" |
|
"Hello world!"
What are the index locations for the substring "Hello"? |
[0,1,2,3,4]
The characters in a string each have a position number called the index location. The first index location starts with zero. |
|
One common string method is .length, which counts how many characters are in a string -- does that character count include spaces? |
Yes, .length tells you how many characters are in the string, including spaces.
|
|
Explain the difference between these two versions of .split, one of the common string methods:
.split .split(argument)
|
.split breaks up the string wherever it encounters a space (" ") character.
If you want to split on a character other than space (like a comma), you must use an argument. ex: .split(",") |
|
Both the common string methods .sub and .gsub can be used to replace parts of a string, like using "Find & Replace" in a word processor. How many arguments do these string methods need to be successful? |
Two. For both sub (substitute) and .gsub (global substitute) you’ll need to specify two arguments: first the substring you’re wanting to replace and second the string you want to replace it with. ex. greeting = "Hello Everyone!" greeting.gsub("Everyone!","Friends!") |
|
Define concatenate.
Cite an example of when something is concatenated in Ruby. |
con·cat·e·nate to link (things) together in a chain or series.
Ex. string concatenation connecting strings and a variable (name): name = "Frank" puts "Good morning, " + name + "!" |
|
Define interpolate.
Cite an example of when something is interpolated in Ruby. |
in·ter·po·late to insert (something) between fixed points.
Ex. string interpolation (which only works on double quoted strings) inserting data into a string using the interpolation marker #{}: name = "Frank" puts "Good morning, #{name}!" Note: Anything inside those brackets will be converted into a string. |
|
Using the following variables, write a puts statement that prints "I am very very very excited for today!" -- use string interpolation with code/calculation inside the interpolation marker brackets:
modifier = "very " mood = "excited"
|
Possible answers: puts "I am #{modifier * 3 + mood} for today!" puts "I am #{modifier * 3}#{mood} for today!"
The snippet between the brackets is evaluated first, then the result is injected into the outer string. Note: you need a space in "very "... |
|
In the following code, capitalize is a ______ called on the _____ named name and assigned to the ______ named text.
text = "#{name.capitalize} has a dog." |
text = "#{name.capitalize} has a dog."
Answer: capitalize is a method called on the object named name and assigned to the variable named text. |
|
In the following code, center is a ______ that takes two _____.
puts text.center(50, '*') |
puts text.center(50, '*')
Answer: center is a method that takes two parameters. |
|
What objects start with a colon, represent names and strings, and have a value that cannot change? |
Symbols. The same Symbol object will be created for a given name or string for the duration of a program's execution, regardless of the context or meaning of that name.
ex. :name, :b, :inigo_montoya |
|
Write a simple loop that repeats the string "Hello, World!" five times. |
5.times do puts "Hello, World!" end
or 5.times{ puts "Hello, World!" }
Note: these answers are both blocks. |
|
In Ruby, what describes characters (either surrounded by braces or starting with do/end) that group a set of instructions together? |
Block.
Blocks are a powerful concept used frequently in Ruby. Think of them as a way of bundling up a set of instructions for use elsewhere. |
|
Blocks can be put between curly braces, but can also begin with the keyword _____ and end with the keyword ___. |
Blocks can begin with the keyword do and end with the keyword end. The do/end style is always acceptable.
ex. 5.times do puts "Hello, World!" end |
|
What will print to the screen if you run this code? "this is a sentence".gsub("e"){|letter| letter.upcase} |
"this is a sentence".gsub("e"){|letter| letter.upcase}
Answer: "this is a sEntEncE" - gsub is using the result of the block as the replacement for the original match. |
|
In Ruby, the most common collection of data is a number-indexed list called an _____. |
Array.
Arrays are created by putting pieces of data between square brackets ([]). They are separated by commas. |
|
Ruby arrays can grow and shrink. You can add an element to the end of an existing array by using what operator? |
The shovel operator (<<).
ex. meals = ["Breakfast", "Lunch", "Dinner"] => ["Breakfast", "Lunch", "Dinner"] meals << "Dessert" => ["Breakfast", "Lunch", "Dinner", "Dessert"] |
|
What is the index location of "Dinner" in the following array?
["Breakfast", "Lunch", "Dinner", "Dessert"] |
Answer: 2
["Breakfast", "Lunch", "Dinner", "Dessert"] 0 1 2 3 |
|
Which common array method returns strings in alphabetical order or numbers in ascending value order. |
Answer: .sort
The sort method will return a new array where the elements are sorted. |
|
Which common array method mashes elements within an array into a single string? |
Answer: .join
The join method returns a string created by converting each element of the array to a string, separated by the given separator.
ex. [ "a", "b", "c" ].join #=> "abc" [ "a", "b", "c" ].join("-") #=> "a-b-c" |
|
You can ask an array if an object is present within the array by using which common array method? |
Answer: .include?
array.include?(object) returns true if the object exists within the array, false if it does not.
ex. a = [ "a", "b", "c" ] a.include?("b") #=> true a.include?("z") #=> false
|
|
Explain the difference between these common array methods:
.each .map (also called .collect) |
Both .each and .map/collect apply the values within a given block once for each element in the array. The difference is that .map/collect returns a new array.
ex. a = [ "a", "b", "c", "d" ] a.each {|x| print x, "*" } #=> a*b*c*d* a.collect { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"] |
|
Explain the difference between zero and nil. |
Zero is something, it’s a number, and it’s not nothing. Nil is nothingness, something that doesn’t exist. If we create a five-element array then asked Ruby to give us the sixth element, Ruby will give us nil. There is no sixth element. It isn’t that there’s a blank in that sixth spot (""), it’s not a number 0, it’s nothingness: nil. |
|
A dictionary-like collection of unique keys and their values is called a ____. |
Hash.
A hash is an unordered collection where the data is organized by name into "key/value pairs".
ex. produce = {"apples" => 3, "oranges" => 1, "carrots" => 12} puts "There are #{produce['oranges']} oranges in the fridge." |
|
In the following code, produce is a ____, apples is a _____ and 3 is a _____. The => is called a _____.
produce = {"apples" => 3, "oranges" => 1, "carrots" => 12} |
produce = {"apples" => 3, "oranges" => 1, "carrots" => 12}
Answer: produce is a hash, apples is a key and 3 is a value. The => is called a hashrocket. |
|
Instead of separating hash elements with a hashrocket, you can use symbols to simplify syntax. Simplify the following hash:
animals = {"elephant" => 9, "monkey" => 15, "sloth" => 2}
|
Original hash: animals = {"elephant" => 9, "monkey" => 15, "sloth" => 2} Simplified hash: animals = {elephant: 9, monkey: 15, sloth: 2}
Notice that the keys end with a colon rather than beginning with one, even though these are symbols. |
|
What do the following operators mean? == && || |
== is a way to question equality. It means "is the thing on the right equal to the thing on the left?" The = used alone attaches something on the left with something on the right (x = y). The == means that x and y are actually equal (x == y).
&& - and ("logical and") ex. if x && y, then z || - or ("logical or") ex. command = "q" || command = "quit" |
|
Conditional statements such as ==, > and < evaluate to _____ or _____. |
True or false. The most common conditional operators: == (equal) > (greater than) >= (greater than or equal to) < (less than) <= (less than or equal to) |
|
In conditional instructions with more than two statements, what comes between if and else? |
Answer: elsif An if statement has one if statement (executed only if the statement is true), zero or more elsif statements (executed only if the statement is true), and zero or one else statement (executed if all other statements are false). Only one section of the if/elsif/else structure can execute. Once one block runs, that’s it. |
|
In Ruby, _____ are used to bundle one or more repeatable statements into a single unit of reusable code that you call by name. |
Method.
In Ruby, methods are used to bundle one or more repeatable statements into a single unit of reusable code that you call by name. |
|
Think of your human self in Ruby terms. You are an _____. If you're in school, you are an instance of the _____ Student. You have _____ like height, weight and eye color. When you "walk", "run", "wash dishes", and "daydream", you are calling _____ on yourself. |
You are an object. If you're in school, you are an instance of the class Student. You have attributes like height, weight and eye color. When you "walk", "run", "wash dishes", and "daydream", you are calling methods on yourself. |
|
In the following code, frank is the _____, Student is the _____ and new is the _____.
frank = Student.new |
In the following code, frank is the variable, Student is the class and new is the method.
frank = Student.new variable = Class.method |
|
Explain what a predicate method is and how it differs from a regular method. |
Unlike a regular method, which applies an action to an object, a predicate method ends in a ? and is asking for a boolean return of true/false. ex. def help? command = "h" || command = "help" end This method asks "Has the user entered h or help?" Next steps depend on a true/false answer. |
|
What is the end result of the following code?
a = %w(taco burrito quesadilla tostada) a.each { |food| puts food} |
Result: taco |
|
There are three different ways to create a new array named "farm" that has the following values: pig, cow, chicken.
Explain/execute all three ways. |
1. make a list: farm = ["pig", "cow", "chicken"] 2. shortcut list, split on whitespace: farm = %w(pig cow chicken) 3. individual steps with shovel operator: farm = Array.new farm << "pig" farm << "cow" farm << "chicken" |
|
Sometimes methods take one or more _____ that tell them how to do what they’re supposed to do. For instance, frank.introduction('Katrina') is a call for Frank to introduce himself to Katrina. |
Sometimes methods take one or more arguments. ex. def introduction(target) puts "Hi #{target}, I'm #{first_name}!" end frank.introduction('Katrina') => "Hi Katrina, I'm Frank!" Note: frank has already been created as a new instance of Student class, first_name has been defined and frank.first_name = "Frank". |
|
If you called the following method, what would print to the screen? "Frank's favorite number is #{frank.favorite_number}." def favorite_number 5 6 7 end |
Answer: 7.
By default, a Ruby method returns the value of the last expression it evaluated. The last line of the favorite_number method is 7. |
|
Objects have a unique _____ and a common set of _____. |
Objects have a unique state and a common set of methods (or behaviors). |
|
An _____ variable exists for the life of an _____. |
An instance variable exists for the life of an object. |
|
A _____ is an abstract description of a category or type of thing. |
Answer: class.
A class is an abstract description of a category or type of thing. For example, if you are in school, you are an instance of the Student class. Your class defines what attributes (ex. first_name) and methods (ex. do_homework) all objects of the student type have. |
|
Write a small Ruby program that asks you what your name is. Have the program print out the number of characters in your name. Also have the program print out a message if your name is longer than 25 characters. |
def small_ruby_program |
|
When writing methods, what is the difference between arguments and parameters? |
The argument is the piece of code you actually put between the method's parentheses when you call it, and the parameter is the name you put between the method's parentheses when you define it. |
|
Array access: print every item in a 2D array |
array = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
array.each do |x| x.each do |y| puts y end
end |
|
Array access: print every item in a 1D array |
friends = ["Milhouse", "Ralph", "Nelson", "Otto"]
friends.each { |x| puts "#{x}" }
or
friends.each { |x| puts x } |
|
Hash syntax |
my_hash = { "tim" => "person", "tim_age" => 31, }
or
my_hash = Hash.new my_hash["tim"] = "person"
or the new 1.9 style
my_hash = { one: 1, two: 2, three: 3 }
|
|
Hash access: print every item in a hash |
my_hash = { "tim" => "person", "tim_age" => 31, }
my_hash.each { |x, y| puts x,y }
or
my_hash.each do |x,y| puts x,y end |
|
Hash access: print each key:value pair in a hash |
my_hash = { "tim" => "person", "tim_age" => 31, }
my_hash.each { |x, y| puts "#{x}: #{y}" }
or
my_hash.each do |x,y| puts "#{x} #{y}" end
|
|
Hash access: print each value in a hash |
lunch_order = { "Ryan" => "wonton soup", "Eric" => "hamburger", }
lunch_order.each do |x,y| puts y end
or
lunch_order.each{|x,y| puts y} |
|
Method: .is_a? |
returns what the object is |
|
Method: .sort |
sorts ascending (1->10) (a-z) |
|
<==> |
combined comparison operator
Returns:
-1 if the first operand should precede the second 0 if they are equal 1 if the first operand should follow the second
1 <=>2 returns -1
a <=> b returns -1 |
|
use <=> and .sort to print out each item in an array in descending order |
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! do |x,y| y <=> x end |
|
Hash: when it comes to a hash's key, what's the difference between a string and a symbol? |
Symbols make good hash keys for a few reasons: 1. They're immutable, meaning they can't be changed once they're created; |
|
Use select to filter a hash |
movie_ratings = { memento: 3, primer: 3.5, the_matrix: 5, truman_show: 4, red_dawn: 1.5, }
good_movies = movie_ratings.select{|movie,grade|grade > 3} |
|
Hash access: print out every key using a method
Hash access: print out every value using a method |
movie_ratings = { memento: 3, primer: 3.5, } movie_ratings.each_key{ |k| print k}
movie_ratings = { memento: 3, primer: 3.5, } movie_ratings.each_value{ |v| print v} |
|
Convert:
to symbol to string to integer |
symbol:
my_item.to_sym or my_item.intern
string: my_item.to_str
integer: my_item.to_i |
|
Hash access: delete a key/value pair |
my_hash.delete(key) |
|
Ternary conditional expression:
Explain the three parts
Explain the syntax |
Variables (local, @instance, @@class, $GLOBAL)
Constants (UPPER_CASE) Keywords (def, if) Method names |
|
Which command will check your .rb file for errors?
|
ruby -cw myfile.rb
It's a mix of -c (check) and -w (a higher level of warning) |
|
Command to find where Ruby is installed
|
rbconfig
|
|
Describe implicit return |
In Ruby, a method will return the result of the last evaluated expression expression (JavaScript and Python don't). |
|
Syntax of a one-line if statement |
if boolean
puts x if true
and:
puts x if x %2 == 0
example:
my_array.each {|x| puts x if x%2 === 0}
|
|
Method sytax and use:
.upto
.downto |
95.upto(100) {|x| print x, " "} =>95, 96, 97, 98, 99, 100
"L".upto("P") {|letter| puts letter, " "} =>L => M => N => O => P |
|
Method syntax and use:
.respondto |
age.respond_to?(:next) =>true |
|
Concatenation operator |
<<
aka "the shovel". Can be used on both arrays and strings.
alphabet = ["a", "b", "c"] alphabet << "d"
caption = "Tim loves" caption << " Anne" |
|
Refactor:
unless n.is_a? Integer return "n must be an integer." end
if n <= 0 return "n must be greater than 0." end |
return "n must be an integer." unless n.is_a? Integer
return "n must be greater than 0." if n <= 0 |
|
Refactor:
prime = Prime.new for num in (1..n) prime_array.push(prime.next) end |
prime = Prime.new n.times {prime_array.push(prime.next)}
and
n.times {prime_array << (prime.next)} |
|
Methods:
.each
vs
.collect |
collect is for when you want to turn one array into another array inject is for when you want to turn an array into a single value [1, 2, 3].each { |x| x + 1 } #=> [1, 2, 3][1, 2, 3].collect { |x| x + 1 } #=> [2, 3, 4] |
|
Syntax:
Use yield in a method without a parameter using a non-predefined block |
def block_test puts "We're in the method!" puts "Yielding to the block..." yield puts "We're back in the method!" end
block_test { puts ">>> We're in the block!" }
=> We're in the method! => Yielding to the block... => >>> We're in the block!
=> We're back in the method! |
|
Syntax:
Define a method with no parameter and use yield to pass a pre-defined block. |
def greeter yield end
phrase = Proc.new {puts "Hello there!"}
greeter(&phrase) => Hello there! |
|
Syntax:
Use yield in a method with a parameter |
def yield_name(name) puts "A" yield("Anne") puts "B" yield(name) puts "C" end
yield_name("Tim") {|n| puts "My name is #{n}"}
=> A => My name is Anne => B => My name is Tim => C
|
|
Describe:
a proc |
You can think of a proc as a "saved" block: just like you can give a bit of code a name and turn it into a method, you can name a block and turn it into a proc. Procs are great for keeping your code DRY, which stands for Don't Repeat Yourself. With blocks, you have to write your code out each time you need it; with a proc, you write your code once and can use it many times!
Why bother saving our blocks as procs? There are two main advantages: 1. Procs are full-fledged objects, so they have all the powers and abilities of objects. (Blocks do not.) 2. Unlike blocks, procs can be called over and over without rewriting them. This prevents you from having to retype the contents of your block every time you need to execute a particular bit of code. We can then pass the proc to a method that would otherwise take a block, and we don't have to rewrite the block over and over! |
|
Syntax:
Define a new proc and call it. |
cube = Proc.new { |x| x ** 3 }
[1, 2, 3].collect!(&cube) => [1, 8, 27]
[4, 5, 6].map!(&cube) => [64, 125, 216]
and
floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911] round_down = Proc.new {|x| x.floor} ints = floats.collect(&round_down) |
|
Method:
.call |
Unlike blocks, we can call procs directly by using Ruby's .call method |
|
Syntax:
Lambda |
lambda { |param| block } |
|
Lambdas vs Procs |
If you're thinking that procs and lambdas look super similar, that's because they are! There are only two main differences. First, a lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assignnil to any that are missing. Second, when a lambda returns, it passes control back to the calling method; when a proc returns, it does so immediately, without going back to the calling method. |
|
Lambda/Proc:
Filter symbols out of an array using lamda and select |
my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages] symbol_filter = lambda {|x| x.is_a? Symbol} symbols = my_array.select(&symbol_filter)
and
odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345] check_int = lambda {|x| x.is_a? Integer} ints = odds_n_ends.select(&check_int) |
|
Review:
block, proc, lambda |
1. A block is just a bit of code between do..end or {}. It's not an object on its own, but it can be passed to methods like .each or.select. |
|
Access REPL from Terminal
|
IRB
|
|
Difference between P, Puts and Print
|
p puts and prints. p will return the evaluated code AND print to the console.
puts will return nil and print the output to the console. print will not add spaces to the end of the outputs. |
|
convert something to float
|
.to_f
|
|
List the four identifiers
|
Variables (local, @instance, @@class, $GLOBAL)
Constants (UPPER_CASE) Keywords (def, if) Method names |
|
Which command will check your .rb file for errors?
|
ruby -cw myfile.rb
It's a mix of -c (check) and -w (a higher level of warning) |
|
Command to find where Ruby is installed
|
rbconfig
|
|
String-formatting methods
|
center
puts("some string".center(5)) ljust (left justify - adds padding) puts("some string".ljust(5)) rjust (right justify - adds padding) puts("some string".rjust(5)) |
|
method for absolute value
|
.abs
|
|
random number generator method
|
rand
default: greater than or equal to 0.0 and less than 1.0 Pass an integer, like rand(5) and it will give an integer greater than or equal to 0 and less than 5 (0, 1, 2, 3, 4) |
|
Tip:
Every object in Ruby will evaluate to true unless it's false or nil. |
a
|
|
Tip:
Ruby always returns the last expression in a method (implicit) unless you state where to return (explicit) |
a
|
|
Every new object is "born" with with abilities, even if not manually given to it.
How would you check what abilities an object has? |
p object.methods.sort (wall of text)
puts object.methods.sort (one per line) |
|
object_id
|
Every Ruby object has a unique ID
Even a number like 100. ID is determined by what it refers to. For example: a = Object.new b = a a and b have the same ID because they refer to the same object. However: a = "hello" b = "hello" a and b have different ID's because they're strings. It's like two copies of the same book. |
|
respond_to?
|
A way to see if an object will respond to a message (eg, a method call, in this case the method 'talk'). It's a way of avoiding an error if you accidentally called a method that an object doesn't know, and gives conditional logic power as well:
obj = Object.new if obj.respont_to? ("talk") obj.talk else puts "Sorry, I don't know the 'talk' message." end |
|
send
|
An all-purpose way of getting a message out of an object so it doesn't have to check the object line-by-line.
def ticket.venue puts warfield end def ticket.price puts $40 end print "What ticket info are you seeking? " request gets.chomp if ticket.respont_to? (request) puts ticket.send(request) else puts "no such info available" end |
|
Difference between a generic and a basic objet
|
Object.mew (generic) comes with a lot of helpful behaviors.
BasicObject.new (basic) comes with only seven behaviors and is missing most the normal methods. Just enough for it to exist as an object, but not much more. |
|
What happens if you pass three arguments to a method that take one?
|
error
|
|
Define a method that takes any number of arguments
|
def method(*x)
stuff end -->the value assigned by using * becomes an array |
|
Define a method that takes two or more arguments
|
def method(a,b,*c)
stuff end * acts like a sponge. It only sops up anything leftover. So if there are non-* args after c (like d, e, f), those will evaluate before *c, leaving only what's left to the C array..Keep in mind the value of the items assigned using * become an array. |
|
Define a method that uses a default argument
|
def method(a,b,c=1)
stuff end |
|
Tip:
Most variables in Ruby do not hold immediate values. They simply contain a reference to a string object. Note: Add a new card (or press TAB)the exception is variables bound to integers |
p56, Well Grounded Rubyst
|
|
Name the types of objects in Ruby that are indeed stored in variables as immediate values.
|
Integers (x=1_
Symbols (:this) True, False, Nil When you assign one of these values to a variable, the variable holds the value itself, rather than a reference to it. |
|
Ruby compares strings alphabetically, also known as ___________
|
Lexigraphically (a,c,b,d,e,..)
It also considers uppercase to come before lowercase, so be sure to use the .downcase method on strings that are being compared. Number characters are in normal order. For example, the strings "2" and "10". The string ten is in theory less than the string two because 1 comes before 2 (again, the character, not number) |
|
Array access:
Access an array at a particular index |
arr.at(x)
|
|
Array access:
how to make it so an error is thrown if the array index is outside the bounds of the array |
fetch
arr.fetch(100) ==> "IndexError" arr.fetch(100,"oops) ==>"oops" |
|
Array access:
Return the first element of an array Return the last element of an array |
arr.first
arr.last |
|
Array access:
return the first n elements of an array return the remaining elements of an array |
arr.drop(n) |
|
Array access:
check if an array includes a specific element |
array.empty?
==> true/false array.include?("Tim") |
|
Array access:
add an item to the end of an array |
arr.push(5)
or arr << 5 |
|
array access:
add an item to the beginning of an array |
arr.unshift(5)
|
|
array access:
at an element to any position of an array |
arr.insert(n, "apple")
arr.insert(n, "apple","pear") |
|
array access:
retrieve and remove the first item |
arr.pop
arr.shift |
|
array acces:
remove an element at a particular index |
arr.delete_at(n)
|
|
array access:
remove all nil elements from an array |
arr.compact!
or arr.compact |
|
array access:
remove all duplicate elements from an array |
arr.uniq!
or arr.uniq |
|
array access:
loop over each item of an array reverse loop over each item |
arr.each { |x| print x}
doesn't change the original array arr.reverse_each {|x| print x} |
|
array access:
loop over each item of an array, and create a new array with the output loop over each item of an array and update the existing array. |
arr.map {|x| 2*x}
arr.map! {|x| 2*x} |
|
array access:
select and return items from an array reject and return items from an array Do this but instead update the original array |
arr.select {|x| x<2}
arr.reject {|x| x>2} arr.select! {|x| x<2} |
|
array access:
delete and return keep and return |
arr.delete_if {|x| x<2}
arr.keep_if {|x| x>2} *has the opposite effect of select/reject |
|
Array access:
lowest highest total length average sorted |
arr.min
arr.max arr.inject(:+) arr.length total.to_f / len arr.sort |
|
array access:
test if an array is: empty nil |
arr.empty?
arr.nil? |
|
array access:
return the smallest number in an array return the largest number in an array |
def smallest(someArr)
return someArr.min end |
|
array access:
return the shortest string in an array return the longest string in an array |
def shortest(someArr)
return someArr.each(|a,b| a.length <=> b.length} end |
|
array access:
concatenate an array |
array1 + array2
or, as a method: def concatenateArr(arr1,arr2) return arr1+arr2 end |
|
Tip: is an array method, just like length and reverse are array methods. Methods that act like loops are called iterators Iterators are always followed by blocks.
Tip: while, end, do, if, else (and others) are not methods, they are keywords. Tip: x.times do is an integer method. Iterators are always followed by blocks. |
a
|
|
Loops:
What statement should you use if you don't know how many times you need to loop? What are some examples of when you don't know how many times you need to loop? |
For example, when you flip a coin, for when you ask someone for a specific input (there's a chance they could keep entering the wrong input). |
|
Control flow: What are the four control flow techniques? |
Conditional execution (based on true/false) Looping (repeat a segment of code) Iteration (method call is supplemented with a segment of code that the method can call on one or more times) Exceptions (error handling) |
|
Control flow: What are the three ways to write an statement? |
if condition #some code end if then end if ; ; end |
|
Control flow: what keyword could you use if you wanted to write an statement that only ran if the condition was not true? |
unless It's like saying "anything but the true/test statement" WGR suggests avoiding unless (and simply negating an if-statement), unless you find a case where it works better. You could instead just invert the condition (!) or you could swap places of the condition (x > 10 versus x<10) |
|
Array method: reduce |
array.reduce(:+) will add each item in the array (5..10).reduce(:+) will add each item in the range |
|
range |
array.each {|a..z| do something} num = 5 array = (1..num).to_a puts array =>[1,2,3,4,5] |
|
Opposite of an if loop |
unless |
|
Opposite of a while loop |
until |
|
How can you code a while loop to ensure it always puts N at least once? |
place the while at the end, and use begin/end: n=10 begin puts n end while n < 10 |
|
Tip: a code block is not an argument. Think of a code block as part of a method's syntax, not as it's argument. |
a |
|
Method blocks: using curly braces around a block is technically not the same as do/end |
Braces almost act like parenthesis, where do/end might come too late, mainly when there's something like "puts" before. If you have puts before a do/end block, it will try to puts the method, causing an enumerator error. OK: puts array.map {|n| n+1} Will error: puts array.map do |n| n+1 end It will try to puts the array.map and will ignore the do/end block. |
|
Arrays and hashes are examples of ____ _____ |
collection objects |
|
Tip: Errors raise an exception. An exception is an instance of the class Exception. All errors are descendants of this class. They're all sub-classes.jjjuujju |
a |
|
Error handling: When an error happens, Ruby either deals with it or aborts. What do you need to supply if you want Ruby to handle exceptions? |
A rescue clause |
|
Error handling: What is Ruby's error handling keyword for when you want to use default handling? What is the syntax? |
rescue Explicit: (begin/end) begin rescue end Implicit: (just end) rescue end |
|
Error handling: What is Ruby's built in keyword for when you want to build your own exception? |
raise |
|
The operator is also known as ____ and is said to entice ______ |
Bang Danger It's a receiver-changing operator. |
|
Tip: Creating new objects (like when you don't use the bang operator) can be expensive as far as resources go. But using bang can also be destructive - other parts of the program might rely on the data. |
a |
|
Tip: What happens if you convert an all-letter string to an integer/float? What happens if you convert this string to an integer? "123abc" What about the string "abc123"? |
Ruby allows it but the result is 0 or 0.0 Ruby ignores the letters, conversion is performed only on the leading digits. The result is 123 or 123.0 Ruby allows it but the result is 0 or 0.0 |
|
What is a stricter way to convert something to integer or float? |
Use the method Float or Integer. Yes, they are capitalized. |
|
Tip: Every expression in Ruby evaluates to an object, and every object has a boolean value of true or false. |
a |
|
Tip: True/fals/nil are objects themselves. That way, an expression like 1<2 can evaluate to something (the objects true/false/nil). True/false can be looked at as both states, as well as special object. Nil isn't an error. It's just a state (and an object), like true and false. And it's value is false. |
a |
|
Nil has a boolean value of _____ |
false |
|
What does scalar mean? |
It means one-dimensional. When used with strings, symbols, integers etc, it means items that have single values, as opposed to being a container holding multiple values (arrays, hashes, etc). |
|
Ruby provides two classes that handle the entirety of text representation and manipulation. They are ____ and _____. |
strings symbols |
|
Strings: difference between using single and double quotes |
Interpolation doesn't work on single-quoted strings. Escaping (\) works differently. |
|
Strings: alternative quoting mechanisms |
%char{text} %q{text} for single quotation mark %Q{text} for double quotation mark |
|
Strings: The + method always returns a new string. How can you permanently add a string to another? |
The append method << |
|
Tip: Interpolation works with any Ruby expression, not just strings. |
"The sum is #{2+2}" => "The sum is 4" |
|
String methods: Which method to tell you how many times a given letter (or set of letters) occurs in a string? Which method to test if a string is blank? Which method to test if a sting contains a specific character or word? Which method to test if a string starts or ends with a certain character or word? |
string.count("str") string.empty? string.include?("str") string.start_with?("str") *all are case-sensitive |
|
String method: .count |
string.count("str") string.count("a-z") string.count("^xyz") (^ negates, so it returns the count of the letters that aren't xyz) |
|
String method: .index |
Returns the index to the left of the first occurrence. string.index("str") You can do this from the right using string.rindex("str") |
|
String method: check the ordinal code of a string check the string at a given ordinal code |
"a".ord ==>97 97.chr =>"a" |
|
Strings: What's the difference between string transformation and string conversion? |
Transformation involves applying some kind of algorithm or procedure to the content of a string. Conversion means deriving a second, unrelated object - usually not even a string - from the string. |
|
Strings: Method examples of transformation |
case (.upcase .downcase .swapcase .caplitalize) format (.rjust .ljust .center .strip .lstrip .rstrip) content (.chop .chomp .clear .replace .delete .crypt .next .succ) |
|
String method: What would you use to get the next letter in the alphabet? |
.succ or .next |
|
String method: what would you use to empty a string of all its contents? what about swap all its contents for a new string? |
.clear .replace |
|
Strings: examples of string conversions |
.to_f .to_s .to_sym .to_i |
|
What are the three main advantages of using symbols as hash keys? |
Ruby can process them fasterThey look good. They give a feeling of being frozen, non-malleable (less prone to errors)They can be written with the colon before or after the name. eg :symbol or symbol:, where the latter is nice for creating a list (eg a key/value pair) |
|
In what two ways are symbols similar and dislike integers? |
ImmutableUnique*because of this, they can't be "changed" like strings can, eg appending new letters. |
|
Name the four container types in Ruby |
Array Hash Range Set |
|
Numbers:Numbers are objects. Describe the family tree of numberic classes. |
Numeric breaks down into floats and integers.Integers break down into fixnums and bignums |
|
In what ways are symbols similar to strings? |
They have a table of methods that share some similarities, like:.capitalize .upcase .empty? .length .sliceWhat's interesting is that indexing a symbol returns a substring, not a symbol. Symbols acknowledge the fact that they're representations of text. |
|
Numbers:What are the characteristics about dividing floats and integers? |
If you divide an integer with an integer, you'll always get an integer.You must feed floating point numbers if you want that as an output (even if it means just adding .0 to the end of the inputs) |
|
Arrays: Name the four ways to create an array |
Array.new literal constructor Array method %w{...} and %i{...} |
|
Array: Array.new |
Array.new() =>[] Array.new(3) => [nil,nil,nil] Array.new(3, "red") =>['red','red','red'] *these are the same objects. To get different objects, do: Array.new(3) { "red" } Array.new(3) {n += 1; n*10} =>[10,20,30] |
|
Array: which array tool could you use to separate a string into an array of words ? |
%W{"tim cannady is fun"} =>["tim","cannady","is","fun"] use %w for single-quotes |
|
Array: which tool could you used to separate a group of characters into an array of symbols? |
i%{ a b c } =>[:a, :b, :c] |
|
Array: What's the difference between << and push? |
Push can take arguments (eg, can push more than one object at a time), whereas the shovel method can only do one object at a time. |
|
Array: When working with two separate arrays, what's the difference between the two methods .push and .concat? |
concat concatenates the array, whereas push will make a 3-d array |
|
Array: What are some ways to join two arrays? |
array1.concat(array2) =>combined arrays => array1 will be a combined array => array2 will be left alone array2 = array1 + [1,2,3] =>combined arrays => array2 will be a combined array => array1 will be left alone |
|
Array: what's the difference between using .replace versus just re-assigning a new array to the variable? |
.replace keeps the same original object, where re-assigning refers a completely new one. .replace is like "keeping the original placeholder so everything around it can still work, just simply replace the value." Reassigning is like saying "forget the old object, look over here instead" a = [1,2,3] b = a a.replace([4,5,6]) a =>[4,5,6] b =>[4,5,6] a = [7,8,9] b =>[4,5,6] |
|
array: what would you use to get rid of nested arrays? And what is the default behavior? |
.flatten Default completely flattens an array. Passing arguments removes layer by layer from the top down (deepest-nested arrays are last last) |
|
array: what happens if you call .join on an array that has mixed types of object elements? |
It will return a string representation of all the elements of the array strung together. |
|
array: what does passing an argument to .join do |
it places the argument between the each pair of elements |
|
array: what's an alternative to the .join method? |
* It looks like multiplication, but it's not. You're actually performing a join operation: a = ['a','b','c'] a * "-" => "a-b-c" |
|
array: which method will return the array with all the duplicate elements removed? |
.uniq |
|
array: what would you use do get rid of all nil elements in an array? |
.compact |
|
array: what's the other method like .length |
.size |
|
array: what method to determine if there's elements present in an array? |
.empty? |
|
array: what method to see if the array has a certain element in it? |
.include? |
|
array: what method to return how many occurrences of a certain item? |
.count(item) |
|
array: which method to return the first n-elements of an array? last n-elements? |
.first(n) .last(n) |
|
Hash tip: Any key and any value can be any Ruby object |
a |
|
Hash: Four ways to create a hash. |
Literal constructor Hash.new Hash.[] method Top-level method whose name is Hash |
|
Hash: literal constructor |
The most common technique. Convenient when you have values you wish to hash that aren't go ing to change. |
|
Hash: Hash.[] class method |
Thanks to syntatic sugar, you can put the arguments to [] directly inside the brackets and dispense them with the method-calling dot: Hash["tim", "TC", "anne", "AN"] => {"tim"=>"TC","anne","AN"} Can pass an array of arrays, too: Hash[[1,2],[3,4],[5,6]] => {1=>2,3=>4,5=>6} |
|
Hash: Name two was to add a key/value pair to a hash. |
Essentially the same technique as an array: state_hash["New York"] = "NY which is the same as: state_hash.[] = ("New York", "NY") Second way: state_hash.store("New York", "NY") |
|
Hash: What happens if you duplicate a key inside a hash? |
The first gets overwritten |
|
Hash tip: The workhorse technique for retrieving hash values is the [] method. Using a hash key is much like indexing an array - except that the index (the key) can be anything, whereas in an array it's always an integer. |
a |
|
Hash: Name the three ways to retrieve value(s) from a hash, and explain which one throws an exception if the key is nonexistent |
california_abbrev = state_hash["California"] => CA california_abbrev = state_hash.fetch("California") => CA two_states = state_hash.values_at("California","Nevada") .fetch will raise an exception, whereas [] gives either nil or a default value. |
|
Hash: Name the two methods to combine hashes, describe their syntax, and describe which is/isn't destructive |
.update (destructive) h1.update(h2) .merge (non-destructive) h3 = h1.merge(h2) |
|
Hash: which method to choose key/value pairs based on the value? which method to ignore? |
.select {|k,v| } .reject {|k,v| } |
|
Hash: which method could you use to remove key/value pairs? |
.delete_if { } .keep_if { } |
|
Hash: which method flips the keys/values? |
.invert (keep in mind keys must be unique. Duplicates will be discarded) |
|
hash: which method to empty a hash? |
.clear |
|
hash: which method to replace a hash with something else? |
.replace({ }) |
|
hash:
what are some methods to see if a hash has a certain key? |
.has_key?(key) .include?(key) .key?(key) .member?(key) |
|
hash: what are some methods to see if a hash has a certain value? |
.has_value?(value) .value?(value) |
|
hash: which method to see if a hash has no keys/values? |
.empty? |
|
hash: which method to list the amount of key/value pairs in a hash? |
.size |
|
Range tip: You can't use range for floating-point numbers because there is, in theory, an infinite amount of values between two whole numbers. Only use range for integers. |
a |
|
Range: What are the two ways to create a range? What is the default of the constructor? |
r = Range.new(1,100) default = inclusive r = Range.new(1,100,true) pass "true" to force exclusive literal syntax: r = 1..100 inclusive r = 1...100 exclusive. Having more dots "pushes" the final number out of range. *don't create 'backwards' ranges. The way it works is by testing if the argument is larger than the first and smaller than the second. If you reverse arrays, this logic will fail (but Ruby will allow it, so don't get confused). |
|
Range: what are the two methods to test inclusion of a value in a range, and what are their differences? |
.cover? Can test strings ("a" and "abc") .include? Can only test individual characters ("a"). It kind of looks at the range as a crypto-array. (aka .member?) *be sure to consider case-sensitivity |
|
Classes: define an instance method |
It's a method defined inside of a class, intended for use by all instances of the class. The don't belong to just one object, they belong to all instances of that class. |
|
Classes: what's the term for a non-instance method? |
a singleton method |
|
Classes: Describe an instance variable |
Begins with @ Only visible to the object they belong Can be used y other methods so long as they belong to/were created within the same class. Unlike a local variable, instance variables retain the value assigned to them even after the method in which they were initialized has terminated. |
|
Classes: Describe setter methods |
Setter methods are ways to assign (or reassign) values to instance variables. There's lots of ways to do this. See WGR p70. One of tricks: when defining a method in a class, use an equals sign after the method's name. This will let you do method calls that look like reassignments: def price=(amount) @price = amount end thedn you can call it like: ticket.price=(63.00) or even ticket.price = 63.00 |
|
Classes: Describe an attribute |
An attribute is a property of an object w hose value can be read and/or written. In the case of the ticket objects, we'd say that each ticket has a price attribute, as well as a date and venue attribute. |
|
Classes: what tool does Ruby provide so you don't have to create repetitive setter methods within a class? For example, so you don't have to write a bunch of read/write setter methods for each of the class' attributes? |
attr_reader :price, :venue, :band attr_writer :price attr_accessor: :x |
|
Classes: how many classes can a Ruby object inherit from? |
Just one. Ruby uses single-inheritance A teacher can be a person, but not also an employee If you want to get into that, use modules. |
|
Classes: describe inheritance and it's limitations |
Inheritance is defined via < class person < human Inheritance in Ruby is single-inheritance. Inheritance often functions more as a convenient way to get two or more classes to share method definitions than as a definitive statement of how real-world objects relate to each other in terms of generality or specificity. |
|
Classes: what's at the top of every class' inheritance tree? |
the Object and BasicObject classes |
|
Classes tip: Remember, classes are objects. Instances are classes of objects. A class object (like ticket) has its own methods, its own state, and its own identity. It doesn't share these things with instances of itself. Sending a message to Ticket (the class) isn't the same as sending a message to instances of Ticket. |
a |
|
Classes: Describe constants and their syntax |
Constants can be used for names of classes. They can also be used to set and preserve important data values in classes. They begin with a capital letter, sometimes all caps. It's possible to perform an assignment on an already-assigned constant, but you'll get a warning. They can referred to from inside the class's instance or class methods. However it's possible to refer to them from outside the class definition by using the special constant lookup notation (::) class Tickets VENUES = ["a","b"]
end puts Tickets::VENUES |
|
Classes: What method to determine whether an objetc has a given class, either as its class or as one of its class's ancestral classes? |
is_a?(Class) examples: String, Array, Person, Human Can be more than one due to inheritance. |
|
Classes: What's the difference between an instance variable and a class variable? |
Instance variable is attached to the object. It uses @. There can be one for every instance. Instance variables are available across methods for any particular instance or object. Class variable is attached to the class. It uses @@. There's only one per class. Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. |
|
Classes: What's the difference between instance methods and class methods? |
Instance methods can access pretty much anything in the class. EG reading/writing instance methods, variables, they can read 'self'. Class methods are less common. You call them through the class, you don't need an instance. They're defined by prefixing it with the class name or with .self |
|
Classes: What do you do if you want each instance of the class to be "set up"? EG starting values for the instance variables |
initialize() Can create custom parameters. It's called by the .new method, for example: Person.new("Tim", 31) |
|
Array: Create sub-arrays of n-length, each with their own name, from a larger array |
def groups_of_n(array) array.each_slice(n).with_index {|group, index| puts "Array Number #{index+1}: #{group,inspect}" } end |
|
Array: two ways to randomize an array |
array.shuffle or if using older versions of Ruby: array.sort_by {rand} |
|
Classes: What do you need to do if you define a class as an enumerator? |
You must define because all methods that come with enumerable are defined in terms of each. In some respects, you might say the whole concept of a "collection" in Ruby is pegged to the enumerable modules and the methods it defines on top of |
|
Hashes: How could you create an array of all a hash's keys? What about an array of all a hash's values? |
hash.keys kash.values |
|
Enumeration: Which method would you use to return the first element in an array that met a certain circumstance? |
array.find { } It returns nil if none are found |
|
Which container object is the most generic and thus the result of most method types? |
arrays |
|
Enumeration: which method could you use to return element in an array that meet a certain circumstance? |
array.find_all { } aka array.select {} It returns an empty array if none are found. Find_all does not have a bang version. Select does. |
|
Enumeration: which method could you use to return all elements of an array that don't meet a certain circumstance? |
array.reject { } it's the opposite of select |
|
Enumeration: explain grep |
I think it basically returns anything that is equal (===) to what you passed it. For example, if you ask it to return all elements that contain the letter o (/o/) or all elements that have whitespace (%w()) It's basically a long-winded form of select and can be thought of like this: enumerable.select {|element| expression === element} grep can take a block as well, so it can select all words that have the letter "o" and then do something to them, like capitalize. |
|
Enumeration: explain group_by |
creates a hash where a key is created for each unique evaluated value (from the block), and the values are an array of the elements that resulted in that key. What's cool is when you pass the block a method that outputs numbers (size, length |
|
Enumerable: describe |
it returns the first thing yielded by each. For example, the first value of an array, or the first key-value pair of a hash |
|
Enumerable: which enumerable classes have a method? |
array and range |
|
Enumerable tip: methods like and can't do much if your method is infinitely-yielding. This is because they don't output until the yielding is done. |
a |
|
Enumerable: which methods would you use if you wanted to grab the first to elements of an array? what if you wanted to grab everything but the first two elements of an array? |
array.take(n) array.drop(n) |
|
Enumerable: describe and describe how you can use them to perform based on non-default criteria |
they return the value based on <=> if you want to do this based on custom criteria, then pass a block arry.min {|a,b| a.size <=> b.size} a more streamlined approach to using a custom block would be to use min_by or max_by: arry.min_by{|a| a.size} |
|
Enumerable: if you call or on a hash, which will be used: the key or the value? |
the key to do it by value, you can do this: hash.min_by{|k,v| v} |
|
Enumerable: describe: each each_index each_with_index with_index each.with_index |
each is each each_index returns the index each_with_index returns the index with_index takes a starting parameter to change the counter for the index. Note it's the counter, not the actual starting position. |
|
Enumerable: what are two different ways you could iterate over characters of a string? |
.split it into an array or keep it as a string and use .each_char |
|
Enumerable tip: strings aren't enumerable in the technical sense - String does not include Enumerable. However Ruby provides necessary tools to traverse them either as characters, bytes, code points and/or line-by-line. |
a |
|
Enumerable: If you have a class and want to be able to sort it amongst others of the same class, you need to do the following: |
define a comparison method for the class (<=>) place the multiple instances in a container sort the container |
|
Enumerable tip: If you want to create a sortable class, you can just put the objects into a container type that already has enumerable (like array or hash). They already have sort and sort_by. |
a |
|
Enumerable: what are the two ways to outline sort behavior? |
define the <=> method (p309 wgr) or pass sort a block (p310 wgr) |
|
OOP: How many scopes are there, and describe them |
CONSTANT = 5 global scope $global = 5 global scope @@class = 5 exist over all instances of the class changing the @@wheels of the Car class changes it for both the Bus car object and the SUV car object. @instance = 5 exist over just that instance of the class
local = 5 |
|
Modules: why use modules over inheritance? |
Because you can mix-in more than one module, while a class can only inherit from one class.
|
|
Modules: Where does the Module class sit in the hierarchy when it comes to the Class class? |
Module sits above the class Class. Kernel is a module that Object mixes in. Object sits below BasicObject. It's in Kernel that most of Ruby's fundamental methods objects are defined. Every class that doesn't have an explicit superclass is a subclass of Object. |
|
Modules: Objects don't "have" methods. Rather they find them by searching modules and classes. |
|
|
Modules: explain the lookup path |
1) modules prepended to its class, in reverse order of prepending
2) its class 3) modules included in its class, in reverse order of inclusion 4) modules prepended to its superclass 5) its class's superclass 6) modules included in its superclass 7) likewise, up to Object (and its mix-in Kernel) and BasicObject |
|
Modules: what's the name of the keyword to call a method from a parent class |
super POODR suggests avoiding it |
|
Modules: modules don't have instances |
It follows that entities or things are generally best modeled in classes, and characteristics or properties of entities or things are best encapsulated in modules. EG: classes are typically nouns, and modules are typically adjectives (stack vs stacklike) |
|
What is an interesting characteristic of For-loops in Ruby? |
The iterator is accessible after the loop is complete. arr = [1, 2, 3] # badfor elem in arr do puts elemend# note that elem is accessible outside of the for loop elem # => 3 # good arr.each { |elem| puts elem } # elem is not accessible outside each's blockelem # => NameError: undefined local variable or method `elem' |