Ruby has a built-in method for this called .split; it takes in a string and returns an array. If we pass it a bit of text in parentheses, .split will divide the string wherever it sees that bit of text, called a delimiter. For example,
text.split(",")
tells Ruby to split up the string text whenever it sees a comma.
www.codecademy.com
Back
How can you create a hash, other way than?
hash = {}
Front
hash = Hash.new
www.codecademy.com
Back
What does the next do in this loop?
i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <= 0
end
Front
i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <= 0
end
Modulo
www.codecademy.com
Back
What do the two methods "gets" and ".chomp" do in the example below?
variable_name = gets.chomp
Front
gets is the Ruby method that gets input from the user. When getting input, Ruby automatically adds a blank line (or newline) after each bit of input; chomp removes that extra line. (Your program will work fine without chomp, but you'll get extra blank lines everywhere.)
www.codecademy.com
Back
What does the interpreter do?
Front
The interpreter is the program that takes the code you write and runs it.
www.codecademy.com
In general, methods that end in ! indicate that the method will modify the object it's called on. Ruby calls these "dangerous methods" because they change state that someone else might have a reference to.
What is the difference between output from print and puts?
Front
The print command just takes whatever you give it and prints it to the screen. puts (for "put string") is slightly different: it adds a new (blank) line after the thing you want it to print.
www.codecademy.com
Back
Is access by index the same thing as index by offset?
Front
yes it is
www.codecademy.com
Back
What is going on here? What would be output?
array = [1,2,3,4,5]
array.each do |x|
x += 10
print "#{x}"
end
Front
10 is being added to each array item
output would be 1112131415
www.codecademy.com
Back
How would extract the key value pairs from the following hash?
family = {
"Homer" => "dad",
"Marge" => "mom",
"Lisa" => "sister",
"Maggie" => "sister",
"Abe" => "grandpa",
"Santa's Little Helper" => "dog"
}
Front
family.each { |x, y| puts "#{x}: #{y}" }
or
family.each do |x, y|
puts "#{x}: #{y}"
end
www.codecademy.com
Back
How can you retrieve what kind of animal is Bowser from the hash?
pets = {
"Stevie" => "cat",
"Bowser" => "hamster",
"Kevin Sorbo" => "fish"
}
Front
pets["Bowser"]
www.codecademy.com
Back
What does "puts" stand for?
Front
print string
www.codecademy.com
Back
Is possible to combine boolean into expressions?
Front
yes, it is!
Combinations like
(x && (y || w)) && z
are not only legal expressions, but are extremely useful tools for your programs.
Expressions in parentheses are always evaluated before anything outside parentheses.
www.codecademy.com
Back
How would you acces "swiss" in the sandwiches array?
sandwiches = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
Front
sandwiches[0][1]
www.codecademy.com
Back
What does a until loop do?
Front
It's sort of like a backwards while: It will execute its code while the condition it checks is false. As soon as that condition becomes true, the loop will end.
www.codecademy.com
Back
What will be the output of this declaration?
"anton".capitalize
Front
"Anton"
www.codecademy.com
Back
How is this operation called and what does it do?
25 % 7 = ?
Front
Modulo
Modulo returns the remainder of division.
For example, 25 % 7 would be 4, since 7 goes into 25 3 times with 4 left over.
www.codecademy.com
Back
When would you use a for loop?
Front
Sometimes you do know how many times you'll be looping, however, and when that's the case, you'll want to use a for loop.
for num in 1...10
puts num
end
www.codecademy.com
Back
What does the method below do?
if string_to_check.include? "substring"
Front
It check if the string contains a substring "substring". If it does found one, it will evaluate to true, otherwise it will evaluate to false.
www.codecademy.com
Back
When we loop over an array or a hash, we say that we ... over it.
Front
iterate
www.codecademy.com
Back
How can you write "foo" backward using a certain method?
How can you check what methods exist for the Greeter objects? How can you exclude ancestors from the list?
class Greeter
...
end
Front
Greeter.instance_methods
In order to exclude ancestors, you may use:
Greeter.instance_methods(false)
https://www.ruby-lang.org/en/documentation/quickstart/3/
Back
To what does the counter equal to using the following operators.
counter = 100
counter += 100 # =>
counter -= 100 # =>
counter *= 100 # =>
counter /= 100 # =>
When will program output "I'm writing Ruby programs!"
unless hungry
puts "I'm writing Ruby programs!"
else
puts "Time to eat!"
end
Front
When variable hungry would equal to false.
www.codecademy.com
Back
Perform a puts using the .times operator to output "foo" 10 times
Front
10.times { puts "foo"}
or
10.times do puts "foo" end
www.codecademy.com
Back
What kind of an array is this?
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Front
multidimensional
www.codecademy.com
Back
How can you get out of this loop?
i = 20
loop do
i -= 1
print "#{i}"
... if i <= 0
end
Front
i = 20
loop do
i -= 1
print "#{i}"
break if i <= 0
end
www.codecademy.com
Back
How can you check the length of the sting "I love ruby"?
Front
"I love ruby".length
www.codecademy.com
Back
To what do method evaluate in Ruby, which end with "?"?
Front
It evaluates to a boolean value, true or false.
www.codecademy.com
Back
What does "anton".capitalize! mean?
Front
fix this card ASAP
www.codecademy.com
Back
How is this operation called and what does it do?
2**3 = ?
Front
Exponentiation
Exponentiation raises one number (the base) to the power of the other (the exponent).
2**3 = ?
222 = 8
www.codecademy.com
Back
What is the difference between:
for num in 1...15
puts num
end
for num in 1..15
puts num
end
Front
for num in 1...15
puts num
end
Will not output 15
for num in 1..15
puts num
end
Will output 15
www.codecademy.com
Back
What does ".gsub!" method stand for? And what does it do?
Front
global substitution
It substitutes a substring, with another one.
string_to_change.gsub!(/s/, "th")
www.codecademy.com
Back
What are good naming conventions for Ruby variables?
Front
Variables should start with a lowercase letter and words should be separated by underscores, like counter and masterful_method. Ruby won't stop you from starting your local variables with other symbols, such as capital letters, $s, or @s, but by convention these mean different things, so it's best to avoid confusion by doing what the Ruby community does.
www.codecademy.com
Back
What does the respond_to? do?
Front
Returns true if obj responds to the given method. Private and protected methods are included in the search only if the optional second parameter evaluates to true.
http://ruby-doc.org/core-2.2.2/Object.html#method-i-respond_to-3F
Write a while loop, which has a variable counter, which = to 1 and add 1 each iteration until variable counter will equal to 11.
Front
counter = 1
while counter < 11
puts counter
counter += 1
end
www.codecademy.com
Back
How can you output a variable with in a string (using string interpolation).
first_name = "Kevin"
Output should be this:
Your name is Kevin
Front
first_name = "Kevin"
puts "Your name is #{first_name}"
www.codecademy.com
Back
What does the "++" and the "--" operator do in Ruby?
Front
Nothing, these operators do not exist in ruby. Use += or -= instead.
www.codecademy.com
Back
What is a hash in Ruby?
Front
A hash is a collection of key-value pairs. Hash syntax looks like this:
hash = {
key1 => value1,
key2 => value2,
key3 => value3
}
Values are assigned to keys using =>. You can use any Ruby object for a key or value.
www.codecademy.com
Back
How do you write a multi-line comment in ruby?
Front
=begin
Hello, there!
I am a very nice comment.
=end
www.codecademy.com
Back
How would you quit irb shell (shortcut)?
Front
ctrl + d
Back
Section 2
(50 cards)
Create a hash called my_hash and give it any default value other than nil.
The combined comparison operator is used to compare two Ruby objects. The combined comparison operator looks like this: <=>. It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.
www.codecademy.com
Back
Create an empty hash called "foo" with a default value "bar"
Front
foo = Hash.new("bar")
www.codecademy.com
Back
Along with false, ... is one of two non-true values in Ruby.
Front
nil
It's important to realize that false and nil are not the same thing: false means "not true," while nil is Ruby's way of saying "nothing at all."
www.codecademy.com
Back
Iterate over an array of an array.
s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
Front
s.each do |x|
x.each do |y|
puts y
end
end
www.codecademy.com
Back
What happens if you try to access a key that doesn't exist, though?
Front
A value of nil will be returned.
www.codecademy.com
Back
If we know the range of numbers, what is a much more Rubyist solution than trying to use a for loop that stops when a counter variable hits a certain value.
Front
we can use .upto and .downto.
www.codecademy.com
Back
What is the name for this expression?
boolean ? Do this if true: Do this if false
puts 3 < 4 ? "3 is less than 4!" : "3 is not less than 4."
Front
ernary conditional expression
www.codecademy.com
Back
If a method takes arguments, we say it ... or ... those arguments.
Front
If a method takes arguments, we say it accepts or expects those arguments.
www.codecademy.com
Back
The hash syntax you've seen so far (with the => symbol between keys and values) is sometimes nicknamed the ... style.
Front
hash rocket
This is because the => looks like a tiny rocket!
www.codecademy.com
Back
Passing a block to a method is a great way of ... certain tasks from the method and defining those tasks when we call the method.
Front
abstracting
www.codecademy.com
Back
Rewrite the hash using the new syntax.
movies = {
:primer => "Awesome",
:memento => "Not as good the 2nd time"
}
Front
movies = {
primer: "Awesome",
memento: "Not as good the 2nd time"
}
www.codecademy.com
Back
Symbols must be valid Ruby variable names, so the first character after the colon has to be a l... or ... ; after that, any combination of letters, numbers, and underscores is allowed.
Front
letter or underscore (_)
www.codecademy.com
Back
Which methods to check if the variable is odd or even?
Front
.odd? and even?
www.codecademy.com
Back
What does CRUD stand for?
Front
C = Create
R = Read
U = Update
D = Delete
www.codecademy.com
Back
The ... , which is the code block that describes the procedures the method carries out. The body is indented two spaces by convention (as with for, if, els if, and else statements)
Front
body
www.codecademy.com
Back
Use a .upto to print out a range of values, from 95 up to 100.
fill in the blanks
case language
... "JS"
puts "Websites!"
... "Python"
puts "Science!"
... "Ruby"
puts "Web apps!"
...
puts "I don'
Front
case language
when "JS"
puts "Websites!"
when "Python"
puts "Science!"
when "Ruby"
puts "Web apps!"
else
puts "I don't know!"
end
www.codecademy.com
Back
Are symbols a string?
Front
No
t's important to remember that symbols aren't strings:
"string" == :string # false
www.codecademy.com
Back
Write a case statement in a more compact way.
case language
when "JS"
puts "Websites!"
when "Python"
puts "Science!"
when "Ruby"
puts "Web apps!"
else
puts "I don't know!"
end
Front
case language
when "JS" then puts "Websites!"
when "Python" then puts "Science!"
when "Ruby" then puts "Web apps!"
else puts "I don't know!"
end
www.codecademy.com
Back
print the whole alphabet using the .upto method
Front
"A".upto("Z") do |letter| puts letter end
www.codecademy.com
Back
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
Create a new array, symbols.
Use .each to iterate over the strings array and convert each string to a symbol, adding those symbols to symbols.
Tip: use the .push method
Front
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
# Add your code below!
symbols = []
strings.each do |x|
symbols.push(x.to_sym)
end
www.codecademy.com
Back
Symbols are immutable, meaning they
a: can't be changed once they're created;
b: can be changed once they're created;
Front
b
www.codecademy.com
Back
A block that is passed into the sort method must return either 1, 0, -1. It should return -1 if the first block parameter should come before the second, 1 if vice versa, and 0 if they are of equal weight, meaning one does not come before the other (i.e. if two values are equal).
Front
Fix this card ASAP
www.codecademy.com
Back
What is the difference between .to_sym and .intern
Front
.intern, while performing precisely the same task, stresses the fact that it gets you the "internal representation" of the string - because Ruby converts all the string literals that you use in the code to symbols internally.
www.codecademy.com
Back
Rewrite this statement in a shorter way.
if true
puts "it is true!"
end
Front
puts "it is true!" if true
www.codecademy.com
Back
Given an literal array my_array = ["foo", "bar", "goo"]
my_hash = Hash.new(0)
Populate the hash with values of the array as keys, and one for each value of the array.
Front
my_array = ["foo", "bar", "goo"]
my_hash = Hash.new(0)
my_array.each do | x |
my_hash[x] += 1
end
www.codecademy.com
Back
What is opposite of the if statement?
Front
The unless statement
www.codecademy.com
Back
What is a splat argument?
Front
Splat arguments are arguments preceded by a *, which signals to Ruby: "Hey Ruby, I don't know how many arguments there are about to be, but it could be more than one."
www.codecademy.com
Back
Is there a difference between the output of the two methods?
def add(a,b)
return a + b
end
def add(a,b)
a + b
end
Front
nope
Ruby's methods will return the result of the last evaluated expression.This is called implicid return
www.codecademy.com
Back
Let's get a little inventive. Write a loop that only puts the even values of my_array. (Bonus points if you use a one-line if!)
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Front
my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_array.each do |x| puts x if x.even? end
www.codecademy.com
Back
Which method would you use in order to conver a string to an integer?
Front
.to_i
www.codecademy.com
Back
Is hash like this valid?
hash = {
"bar" => 1
"bar" => 2
}
Front
No, the keys must be unique
www.codecademy.com
Back
How can you delete movie Leon from the movie hash?
movies = {
Leon: 5,
Horsey: 3,
Pulpfiction: 5
}
puts "Please enter title movie"
title = gets.chomp.upcase
...
Front
movies = {
Leon: 5,
Horsey: 3,
Pulpfiction: 5
}
puts "Please enter title movie"
title = gets.chomp.upcase
...
movies.delete(title)
www.codecademy.com
Back
What does the .push method do?
Front
It adds an element to the end of an array.
www.codecademy.com
Back
What method would you use in order convert a string to a symbol?
Front
.to_sym
www.codecademy.com
Back
What is the output of this array?
my_array = [5, 6, 2, 1].sort!
Front
[1, 2, 5, 6]
www.codecademy.com
Back
What methods would you use in order to iterate over just keys or just values?
What is the difference between an argument and a parameter?
Front
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.
www.codecademy.com
Back
Sort books in descending order.
books = ["Charlie and the Chocolate Factory", "War an
d Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
Front
books = ["Charlie and the Chocolate Factory", "War an
d Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
books.sort! { |firstBook, secondBook| secondBook <=> firstBook}
www.codecademy.com
Back
How can sort o string with the greatest value to be on top?
frequencies = {
"foo" => 1
"bar" => 2
"goo" => 3
}
Front
frequencies = frequencies.sort_by {|a, b| b}
frequencies.reverse!
or
frequencies = frequencies.sort_by do |foo, count|
count
end
frequencies.reverse!
www.codecademy.com
Back
Sort books in ascending order.
books = [
"Charlie and the Chocolate Factory",
"War and Peace",
"Utopia",
"A Brief History of Time",
"A Wrinkle in Time"
]
Front
books = ["Charlie and the Chocolate Factory", "War an
d Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]
books.sort! { |firstBook, secondBook| firstBook <=> secondBook }
www.codecademy.com
Back
The ..., which includes the def keyword, the name of the method, and any arguments the method takes.
Front
header
www.codecademy.com
Back
What is another name for the combined comparison?
Front
spaship operator
www.codecademy.com
Back
What does the conditional assignment operator do?
||=
Front
It will only assign a variable if it hasn't already been assigned. In other word if the value of the variable equals to nil.
www.codecademy.com
Back
What does the .to_s method do?
puts word + " " + value.to_s
Front
Converts value to string.
www.codecademy.com
Back
Which keyword do you have to use in order to define a method?
Front
def
www.codecademy.com
Back
What does return do?
Front
The return keyword handles the method's output. The method won't print anything out, but it will hand us back the result of our computation.
www.codecademy.com
Back
Define a method called "doit" with two parameters "foo" and "bar". Set second parameter "bar" to false as default.
Front
def doit(foo, bar=false)
# do something
end
www.codecademy.com
Back
What does the .select method do?
Front
The .select method takes a block consisting of a key/value pair and an expression for selecting matching keys and values.
grades = { alice: 100,
bob: 92,
chris: 95,
dave: 97
}
grades.select { |k,v| k > :c }
# ==> {:chris=>95, :dave=>97}
grades.select { |k,v| v < 97 }
# ==> {:bob=>92, :chris=>95} www.codecademy.com
Back
Section 3
(50 cards)
Get the crew names, which are the first half of the alfabet using a lambda (unto "M").
crew = {
captain: "Picard",
first_officer: "Riker",
lt_cdr: "Data",
lt: "Worf",
ensign: "Ro",
counselor: "Troi",
chief_engineer: "LaForge",
doctor: "Crusher"
}
You can think of modules as being very much like classes, only modules can't create instances and can't have subclasses. They're just used to store things!
www.codecademy.com
Back
Covert to strings using a lambda.
strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
# Write your code below this line!
...
# Write your code above this line!
symbols = strings.collect(&symbolize)
Front
strings = ["leonardo", "donatello", "raphael", "michaelangelo"]
# Write your code below this line!
symbolize = lambda { |string| string.to_sym }
# Write your code above this line!
symbols = strings.collect(&symbolize)
www.codecademy.com
Back
When a module is used to mix additional behavior and information into a class, it's called a ... .
Front
When a module is used to mix additional behavior and information into a class, it's called a mixin.
www.codecademy.com
Back
Create a instance of a class using your name.
class Person
def initialize(name)
@name = name
end
end
Front
class Person
def initialize(name)
@name = name
end
end
me = Person.new("Eric")
www.codecademy.com
Back
How would you check if array would .respond_to? a push method?
my_array = [1, 2, 3]
Front
my_array.respond_to?(:push)
www.codecademy.com
Back
What does the .respond_to? method do?
Front
Checks if an object responds to a certain method.
[1, 2, 3].respond_to?(:push)
www.codecademy.com
Back
What is a Proc? How would you create one?
Front
You can think of a proc as a "saved" block.
Proc.new {}
cube = Proc.new { |x| x ** 3 }
www.codecademy.com
Back
q: What other names could you use for the base class?
Front
a: parent class, superclass
www.codecademy.com
Back
@@users is a class variable, use a class method to grab it.
class Computer
@@users = {}
end
Front
class Computer
@@users = {}
def Computer.get_users
@@users
end
end
www.codecademy.com
Back
review: blocks and lambdas
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.
A proc is a saved block we can use over and over.
A lambda is just like a proc, only it cares about the number of arguments it gets and it returns to its calling method rather than returning immediately.
Front
www.codecademy.com
Back
Why bother saving our blocks as procs? There are two main advantages:
Front
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.
www.codecademy.com
Back
Fill in the blanck.
:hello.is_a? ...
# ==> true
Front
:hello.is_a? Symbol
# ==> true
www.codecademy.com
Back
What is an explicit receiver?
Front
These are the objects on which methods are called! Whenever you call object.method, object is the receiver of the method.
www.codecademy.com
Back
As an example create a Proc where you get multiples of three.
...
(1..100).to_a.select(&multiples_of_3)
Front
multiples_of_3 = Proc.new do |n|
n % 3 == 0
end
(1..100).to_a.select(&multiples_of_3)
www.codecademy.com
Back
What are the only two main differences between a Proc and Lambda?
Front
First, a lambda checks the number of arguments passed to it, while a proc does not.
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.
www.codecademy.com
Back
Use collect or map to create the strings_array from the numbers_array. Each element of strings_array should be the string version of the corresponding element from the numbers_array (that is, it should go ["1", "2", "3"... "10"]).
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
What does the "&" do?
cube = Proc.new { |x| x ** 3 }
[1, 2, 3].collect!(&cube)
Front
The & is used to convert the cube proc into a block (since .collect! normally take a block).
www.codecademy.com
Back
What is a module?
Front
You can think of a module as a toolbox that contains a set methods and constants.
www.codecademy.com
Back
How can you acces and write attributes in a Ruby class?
Front
Use attr_reader to access a variable and attr_writer.
class Person
attr_reader :name
attr_writer :name
def initialize(name)
@name = name
end
end
www.codecademy.com
Back
Are blocks in Ruby objects?
Front
Blocks are the one thing, which are not objects in Ruby.
Because of this, blocks can't be saved to variables and don't have all the powers and abilities of a real object.
www.codecademy.com
Back
Let's get some practice in with an existing Ruby module: Math. Use the scope resolution operator to puts the value of PI from the Math module to the console.
Front
puts Math::PI
www.codecademy.com
Back
q: How can you write this on one line?
class Dragon < Creature
end
Front
a: class Dragon < Creature; end
www.codecademy.com
Back
create a new class called NewClass
Front
class NewClass
# code
end
www.codecademy.com
Back
Declare a variable called time and set it equal to the current time.
Front
time = Time.now
www.codecademy.com
Back
What does the .collect method do?
Front
The collect method takes a block and applies the expression in the block to every element in an array. It returns a copy of an array, but does not change/mutate the original.
my_nums = [1, 2, 3]
my_nums.collect { |num| num ** 2 }
# ==> [1, 4, 9]
Mutating could be done by using "!"
my_nums.collect! {|num| num ** 2}
www.codecademy.com
Back
refactor
class Person
def initialize(name, job)
@name = name
@job = job
end
def job=(new_job)
@job = new_job
end
end
Front
class Person
attr_writer :job
def initialize(name, job)
@name = name
@job = job
end
end
www.codecademy.com
Back
q: Which class is the derived class and which is the base class?
class FooClass < BarClass
# Some stuff!
end
Front
class DerivedClass < BaseClass
# Some stuff!
end
www.codecademy.com
Back
refactor
class Person
def initialize(name, job)
@name = name
@job = job
end
def name
@name
end
end
Front
class Person
attr_reader :name
def initialize(name, job)
@name = name
@job = job
end
end
www.codecademy.com
Back
What is the difference between a public and a private methods of a class?
Front
Public method can be called from outside the class. Private method on the other hand can't.
www.codecademy.com
Back
What does the .floor method do?
Front
The .floor method rounds a float (a number with a decimal) down to the nearest integer.
www.codecademy.com
Back
If you want to read and write a particular variable of clas what would you use instead of attr_reader and attr_writer?
Front
attr_accessor
www.codecademy.com
Back
How can you bring in a non existing module in the interpreter? The name of the module is "bar"
Front
require 'bar'
www.codecademy.com
Back
Name the variable types.
@varible # =>
@@variable # =>
$varible #=>
Front
@varible # => instance variable
@@variable # => class variable
$varible #=> global variable
www.codecademy.com
Back
Instead of typing out the .push method name, you can simply use ... , the concatenation operator (also known as "the shovel") to add an element to the end of an array.
Front
Instead of typing out the .push method name, you can simply use <<, the concatenation operator (also known as "the shovel") to add an element to the end of an array.
[1, 2, 3] << 4
# ==> [1, 2, 3, 4]
www.codecademy.com
Back
q: How would you override the fight class in the Dragon class?
class Creature
def fight
return "Punch to the chops!"
end
end
class Dragon < Creature
..
end
Front
class Dragon < Creature
def fight
return "Breathes fire!"
end
end
Back
q: When you overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need, how can you acces it?
Front
a:
class DerivedClass < Base
def some_method
super(optional args)
# Some stuff
end
end
end
www.codecademy.com
Back
q: Let's say we have class ApplicationError and would like a new class BadError to inherit from it. How would you do it?
class ApplicationError
def display_error
puts "Error! Error!"
end
end
Front
class ApplicationError
def display_error
puts "Error! Error!"
end
end
class SuperBadError < ApplicationError
end
err = SuperBadError.new
err.display_error www.codecademy.com
Back
How is this is called?
@name
Front
Instance variable. This means that the variable is attached to the instance of the class.
www.codecademy.com
Back
What objects in Ruby are written in all caps using underscores?
Front
constants
www.codecademy.com
Back
q: How would you keep track of number of instances that a class created?
class Person
@@people_count = 0
def initialize(name)
@name = name
...
end
...
end
puts "Number of Person instances: #{Person.number_of_instances}"
Front
class Person
@@people_count = 0
def initialize(name)
@name = name
@@people_count += 1
end
def self.number_of_instances
@@people_count
end
end
Back
One of the main purposes of modules is to separate methods and constants into n...d s...s. This is called (conveniently enough) ..., and it's how Ruby doesn't confuse Math::PI and Circle::PI.
Front
One of the main purposes of modules is to separate methods and constants into named spaces. This is called (conveniently enough) namespacing, and it's how Ruby doesn't confuse Math::PI and Circle::PI.
www.codecademy.com
Back
What does extend do?
Front
Whereas include mixes a module's methods in at the instance level (allowing instances of a particular class to use the methods), the extend keyword mixes a module's methods at the class level. This means that class itself can use the methods, as opposed to instances of the class.
www.codecademy.com
Back
How does the .each method differ from the .collect method?
Front
Array#each takes an array and apply the given block over all the items. And it doesn't affect or produce the new object. Its just a way of looping items. Also it returns self.
Array#collect is same as Array#map and it applies the given block of code over all the items and returns the new array. simply put 'Projects each element of a sequence into a new form'.
http://stackoverflow.com/questions/5347949/whats-different-between-each-and-collect-method-in-ruby
Back
What would be output of this?
def my_method
puts "reached the top"
yield
puts "reached the bottom"
end
my_method do
puts "reached yield"
end
Front
reached the top
reached yield
reached the bottom
=> nil
http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes
Back
q: May a Ruby class have more than one parent?
Front
a: no
www.codecademy.com
Back
How is this operator called? (the two colon thingy)
Circle::PI
Front
scope resolution operator
www.codecademy.com
Back
Because modules can't be instantiated, we can't just use def some_name. That will make an instance method! Instead, we'll want to create methods at the class/module level. Solve this problem by by explicitly calling the method on the module
module Circle
def ... .area ...
PI radius*2
end
Front
module Circle
def Circle.area(radius)
PI radius*2
end
module Circle
def self.area(radius)
PI radius*2
end
www.codecademy.com
Back
If you have created a new Proc. What is an easy way to call it?
hi = Proc.new { puts "Hello!" }
Front
hi.call
www.codecademy.com
Back
What happens when you include a module?
Front
When we include a module that has already been required, we pull in all its methods and constants at the instance level. That means that any class that includes a certain module can create objects (instances) that can use those very same methods!
www.codecademy.com