Section 1

Preview this deck

use the between? method, which takes two arguments, to see if the number 2 lies between 1 and 3.

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (115)

Section 1

(50 cards)

use the between? method, which takes two arguments, to see if the number 2 lies between 1 and 3.

Front

2.between?(1,3)

Back

Objects may interact by using _______, in this sense: one object may call or invoke the ________ of another object.

Front

methods

Back

Check to see if this string below starts with 'Ruby'. "Ruby is a beautiful language"

Front

"Ruby is a beautiful language".start_with?("Ruby")

Back

What are two ways to create an array?

Front

[] Array.new (does the same thing)

Back

Convert this string to uppercase: "i am in lowercase"

Front

"i am in lowercase".upcase

Back

Placeholders in interpolated strings aren't just variables; they will evaluate any valid block of Ruby code. Add to the single line of code within this method to make it work: def string_length_interpolator(incoming_string) "This string has a length of ___________" end

Front

def string_length_interpolator(incoming_string) "This string has a length of ...#{incoming_string.length}" end I included the entire function. Notice that the interpolated placeholder contains code that Ruby is interpreting. (the length method operating on the incoming_string argument)

Back

write expression to test whether age is less than or equal to 35

Front

age <= 35 # will return true or false

Back

write an expression that accepts any name except "Bob"

Front

!(name == "Bob")

Back

The additional information you supply to a method, for example the string 'bobby' supplied to the index method here: ['hi', 'there', 'bobby'].index('bobby'), is called....

Front

an argument, or arguments, because there are often more than one.

Back

check to see whether the value of the variable name is "Bob"

Front

name == "Bob" # will return true or false

Back

Use a Regex to find a substring. In this string, how would you find the first character that is preceded by a space? 'RubyMonk Is Pretty Brilliant'

Front

'RubyMonk Is Pretty Brilliant'.match(/ ./) This will return ' I' # a space followed by capital i What's going on here: within the regex is a space, followed by a period. The period is a special character in regexes that means "match any character except a new line" Anyway just file this away

Back

Given the string 'RubyMonk', use the gsub method and a regular expression to replace all vowels with the number 1.

Front

'RubyMonk'.gsub(/[aeiou]/,'1') #regular expressions can be intimidating but you really need to get comfortable with them

Back

Use the mathematical operator + to add 3 to 4, but invoke the operator with a period upon the object 3. (just to show that you can do this)

Front

3.+(4) It is the same as 3+4 Ruby makes syntactic exceptions for commonly used operators such as + - * / = == != > < >= <= []

Back

Write an expression testing whether age is greater than or equal to 23 and name is either "Bob" or "Jill"

Front

age >= 23 && (name == "Bob" || name == "Jill") # remember to use parentheses to remove any doubt about precedence . && is AND and || is OR

Back

Use the [] method twice, once with a . and once without to access the second element of an array, foo

Front

foo.[](1) #I've never seen this done in real life foo[1] #this is what you will see (remember array indices start with 0 in ruby)

Back

How would you get a listing of all the methods that the object 1 has, but sorted?

Front

1.methods.sort

Back

Invoking a method on an object generates a response, which is always another _________

Front

object

Back

write the missing code below to ring the bell (bell.ring) n times def ring(bell, n) # what goes here? end

Front

def ring(bell, n) n.times do bell.ring end end

Back

Given this array, [1, 2, 3, 4, 5] what method can give the result of this array: [3, 6, 9, 12, 15]?

Front

[1, 2, 3, 4, 5].map { |i| i * 3} or [1, 2, 3, 4, 5].collect { |i| i * 3}

Back

Create an array with the numbers 1 through 4

Front

[1,2,3,4]

Back

In Ruby, how do you specify a regular expression, syntactically?

Front

You put it between two forward slashes. Ex: /hi/

Back

reference the 3rd value in this array: [1,2,5,8,10]

Front

[1,2,5,8,10][2] returns 5 # remember array indices begin with 0 so the third element has an index of 2.

Back

Determine the length of the string 'Yeahbuddy'

Front

'Yeahbuddy'.length #double quotes are fine too

Back

Given names = ['rock', 'paper', 'scissors', 'lizard', 'spock'] extract from this array the strings that are longer than 5 characters, in an array

Front

names.select {|name| name.length > 5} # select is helpful for filtering elements

Back

print "meow" eight times

Front

8.times do puts "meow" end

Back

How would you call match on this string, looking for a space followed by anything, starting at position 10? 'RubyMonk Is Pretty Brilliant'

Front

'RubyMonk Is Pretty Brilliant'.match(/ ./, 10) #the second parameter tells match where to start looking in the target string, in this case, position 10

Back

Replacing placeholders in a string with the values those placeholders represent is called....

Front

"string interpolation". A common term that you should remember.

Back

What is the output of the two statements below: if nil puts "hey there nillo!" end if 0 puts "what's up zero!" end

Front

The first has no output, because nil, like false, equates to false, so the puts statement is not executed. Every other object is "true" to ruby, including 0, so the output of the second if-then clause is "what's up zero!" because 0 evals to true

Back

Fix this code below so that when the number passed in is 0, it just prints 0: def check_sign(number) if number > 0 "#{number} is positive" else "#{number} is negative" end end

Front

def check_sign(number) if number > 0 "#{number} is positive" elsif number == 0 "0" else "#{number} is negative" end end

Back

Suppose: a = 1 b = 2 How would we get a string that says "The number 1 is less than 2" but using string interpolation to insert the values for a and b in the string?

Front

"the number #{a} is less than the number #{b}" double quotes are necessary! single quoted strings do not support interpolation.

Back

Show three ways to add two strings, 'hi' and 'there' together: What is this called?

Front

'hi' + 'there' 'hi' << 'there' 'hi'.concat('there') #all three above lines will produce the string 'hithere' It is called "concatenating" which is a word you should know

Back

Replace all occurences of 'I' with 'We' in this string: "I should look into your problem when I get time"

Front

"I should look into your problem when I get time".gsub('I','We')

Back

given a loop where a cat object is eating (cat.eat) use a break statement to exit the loop once the cat is full (cat.full?)

Front

loop do cat.eat if cat.full? break end end

Back

Convert this string to lower case: "I am ALL over the Place"

Front

"I am ALL over the Place".downcase

Back

Replace all the capital case letters in this string with the number '0': 'RubyMonk Is Pretty Brilliant'

Front

'RubyMonk Is Pretty Brilliant'.gsub(/[A-Z]/,'0') # in a regular expression you can specify a range, as above. For example /0-9/ would match any number

Back

To know which object you are at the moment, you may use the keyword ________

Front

self

Back

What does "ternary" mean? What is Ruby's ternary operator? Given an existing variable, number, use it to return "positive" or "negative" based on whether it is such.

Front

it means "composed of three items". number > 0 ? "positive" : "negative" # before the ? is the if, between ? and : is the "then" and after the : is the "else" it makes sense once you see it a few times.

Back

Replace 'I' with 'We' in this string: "I should look into your problem when I get time"

Front

"I should look into your problem when I get time".sub('I','We') # of course this will only replace the first occurence of 'I'

Back

The unless keyword can check for a negative condition. write an unless statement that outputs "Grow up!" if the value of an existing age variable is less than 18.

Front

unless age >= 18 puts "Grow up!" end # you don't see unless often

Back

How can you tell whether this string below contains the word "soda"? "I really hate milk, coffee, and soda. I only like water"

Front

"I really hate milk, coffee, and soda. I only like water".include?('soda') Obviously there are many ways to do this; the above is probably the simplest.

Back

extract the last value in this array: [1,2,5,8,10]

Front

[1,2,5,8,10][-1] returns 10. To get teh 2nd to last value: [1,2,5,8,10][-2] which would return 8

Back

If you want to know what methods an object provides, you should....

Front

call the "methods" method on the object. Ex: 1.methods

Back

write a simple loop statement that will print "waa" for all time and never end.

Front

loop do puts "waa" end # this has no termination condition and will go on forever

Back

You can "chain" invocations by adding periods and further method names. How would you invoke the "next" method twice on 1 to get 3? to get 5?

Front

1.next.next 1.next.next.next.next

Back

Check to see if this string below ends with 'Ruby'. "I can't work with any language except Ruby"

Front

"I can't work with any language except Ruby".end_with?("Ruby")

Back

Can Ruby arrays contain mixed types? For example numbers and strings?

Front

Oh yes. [1,2,'three'] is perfectly valid

Back

Find the index of 'L' in the string below: "I am not a Loser so stop saying that!"

Front

"I am not a Loser so stop saying that!".index('L')

Back

convert this string into an array of words: "How do I do this very hard task?"

Front

"How do I do this very hard task?".split # this will create an array splitting on ' ' which is the default for the split method

Back

One Ruby convention is that any method that ends with a ? returns only _______

Front

boolean values (true or false)

Back

What are two ways to add the string "woot" to this array: [1,2,5,8,10]

Front

[1,2,5,8,10] << "woot" [1,2,5,8,10].push ('woot') gives us [1,2,5,8,10, "woot"]

Back

Section 2

(50 cards)

given an array number_list, delete all even numbers from it

Front

number_list.delete_if { |i| i % 2 == 0}

Back

Create a hash (restaurant_menu) with these keys and values Ramen = 3 Dal Makhani = 4 Tea = 2

Front

restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Tea" => 2}

Back

Given restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 } use the each method on this hash to raise the prices of all items by 10%

Front

restaurant_menu.each do |item, price| restaurant_menu[item] = price + (price * 0.1) end

Back

What will this code do? def demonstrate_early_return return puts "I love potatoes!" end

Front

It will do nothing, returning a nil, because it exits the method after the return statement.

Back

What does this code do: def add(*numbers) numbers.inject(0) { |sum, number| sum + number } end puts add(1) puts add(1, 2) puts add(1, 2, 3) puts add(1, 2, 3, 4)

Front

1 3 6 10 The inject method on the numbers array looks scary. All it does is add all the elements in the array together.

Back

How do you set a "default" value for a hash?

Front

When you create it, pass in the default value. ex: somehash = Hash.new('black') somehash[:not_a_key] would return "black" instead of nil

Back

I want to test if something is a string class....

Front

object.is_a?(String)

Back

You can create a new hash with the [] operator and pass in a list of items, or an array of two element arrays, or a bunch of key value pairs. Which of these is not true?

Front

They are all true. newhash = Hash["somekey" => "somevalue"] newhash = Hash["somekey", "somevalue", 1, 3] newhash = Hash[[[1,4],[3,9]]]

Back

Given an existing restaurant_menu hash, how would you assign 2 to the price of "Tea"? (assume the names are the keys and the prices are the values)

Front

restaurant_menu["Tea"] = 2

Back

What will this output, and why? def add(a_number, another_number, yet_another_number = 5) a_number + another_number + yet_another_number end puts add(1, 2) puts add(1,2,3)

Front

8 6 The first call to add leaves off the third parameter. But in the method definition, the third parameter has a default value of 5, so that is used in the absence of an explicit third parameter. The second call passes in the third parameter, so that value (3) is used.

Back

What will this code do? next_method_object = 1.method("next") puts next_method_object.call

Front

It will output 2; the next_method_object retains its relationship to the object to which it belongs

Back

The return keyword specifies the __________________________ when the method has done its work

Front

object to be returned to the caller

Back

Hashes are sometimes called _________ arrays

Front

associative

Back

All objects in Ruby expose the _______ method that can be used to get hold of any of its methods as an object.

Front

method ex: 1.method("next")

Back

Given a restaurant_menu hash with item names as keys, how would you find the price (value) of "Ramen"?

Front

restaurant_menu["Ramen"]

Back

what code would define a simple class called "rectangle"

Front

class Rectangle end #remember classes need to be uppercase

Back

How can you ask whether an object is a particular class?

Front

is_a? method. ex: 1.is_a?(Integer) 1.is_a?(String)

Back

copy values less than 4 in an array stored in the source variable into an array in the destination variable. use a for loop. def array_copy(source) destination = [] #fill in code end

Front

def array_copy(source) destination = [] for i in source destination << i if i < 4 end return destination end

Back

copy values less than 4 in an array stored in the source variable into an array in the destination variable. use the each method. def array_copy(source) destination = [] #fill in code end

Front

def array_copy(source) destination = [] source.each do |i| destination << i if i < 4 end return destination end

Back

array = [1, 2, 3, 4, 5] use each to print each item in the array

Front

array.each do |i| puts i end

Back

If no return keyword is specified in a method, what will be returned by the method?

Front

the object created by the last line in the method will be returned; a method must always return exactly one object

Back

What is a lambda?

Front

In Ruby, a lambda is just a function without a name.

Back

Classes are sort of like f________ that build o______.

Front

factories that build objects

Back

What will this code output? def add(a_number, another_number) a_number + another_number end puts add(1, 2)

Front

3

Back

Calling the ____ method on a class results in an instance being created

Front

new

Back

An object built by a certain class is called an __________ of that class

Front

instance

Back

What will this output, and why? 1.class.class

Front

Class because even the classes are objects of the class Class

Back

How can I determine what class an object is?

Front

1.class "".class etc.

Back

How would you get an array of all the keys, or values in a hash, respectively?

Front

Hash.keys Hash.values #return arrays

Back

If you consider classes as the "factories" that build objects, an object built by a certain class is called an ______ of that class

Front

instance

Back

What will this output, and why? 1.class.class

Front

Class because classes themselves are simply objects that belong to the class "Class"

Back

delete the element 5 from this array [1,3,5,4,6,7]

Front

[1,3,5,4,6,7].delete(5)

Back

Write a method called add_two that adds 2 to any number passed to it and returns the result.

Front

def add_two(a_number) a_number.next.next end # you could also just say a_number + 2

Back

Given [1,3,5,4,6,7] delete all elements less than 4 in this array

Front

[1,3,5,4,6,7].delete_if{ |i| i < 4}

Back

What will this do, and why? next_method_object = 1.method("next") puts next_method_object.call

Front

output "2" because a method object maintains a relationship with the object to which it belongs.

Back

How can you access an object's method as an object?

Front

use the method method. :) 1.method("next") will return a method object

Back

l = lambda { "Do or do not" } puts l.call What will this output?

Front

"Do or do not" invoking the "call" method on the lambda object l

Back

A Hash is a collection of k___ v_____ pairs

Front

key value

Back

How do you declare a blank hash?

Front

{}

Back

Find out the class of any object by...

Front

calling the "class" method on it; 1.class [].class etc

Back

Write the area method for this class below: class Rectangle def initialize(length, breadth) @length = length @breadth = breadth end def perimeter 2 * (@length + @breadth) end #write the 'area' method here end

Front

class Rectangle def initialize(length, breadth) @length = length @breadth = breadth end def perimeter 2 * (@length + @breadth) end #write the 'area' method here def area @length * @breadth end end

Back

What does it mean when the variable names in a class definition have an @ in front of them?

Front

It is a convention that indicates that those variables are "instance" variables of the class. Which means every "instance" of the class Rectangle will have its own copies of those variables and could be a distinct rectangle.

Back

array = [1, 2, 3, 4, 5] use a for loop to print each item in array

Front

for i in array puts i end

Back

Sometimes methods will have a variable parameter list. To handle this, we use the _____ operator

Front

splat *

Back

Given this: def add(a_number, another_number, yet_another_number) a_number + another_number + yet_another_number end numbers_to_add = [1, 2, 3] How do we call the add method and pass in numbers_to_add?

Front

add(*numbers_to_add) The splat will convert the collection into 3 distinct parameters

Back

calling return will ______ the method at that point

Front

exit # no code after the return statement will be executed

Back

For a class to have meaning, it needs to have two distinct features: s______________ and b________.

Front

State and behaviour. State might be the attributes of its instances. For example a Rectangle class might have a rectangle instance with a width and length as attributes. Behaviour is achieved by the programming defining methods to the class to interact with its state, generally. like area and perimeter, in the case of a rectangle object.

Back

What will this code output? def add(a_number, another_number, yet_another_number) a_number + another_number + yet_another_number end puts add(1, 2, 3)

Front

6

Back

To make for a prettier method invocation, if the last parameter in a parameter list is a hash, you can ____________

Front

skip the curly braces when you call the method. Ex: add(1.0134, -5.568, absolute: true, round: true, precision: 2)

Back

Good practice of the return statement is to always use return in the ______________________

Front

very last line of the method. Otherwise it can be confusing.

Back

Section 3

(15 cards)

you can pass File.open a block which will....

Front

auto-close the file you opened once you are done: File.open("clean-slate.txt", "w") do |file| file.puts "Call me Ishmael." end

Back

How do you go to a particular byte in the file?

Front

File#seek p File.read("monk") File.open("monk") do |f| f.seek(20, IO::SEEK_SET) p f.read(10) end

Back

you include a module in a class by ____

Front

using the "include" method which takes one parameter, the name of a module. ex: class Gym include WarmUp end

Back

# What is going on here? l = lambda do |string| if string == "try" return "There's no such thing" else return "Do or do not." end end puts l.call("try")

Front

Lambdas can take parameters by surrounding them with pipes, so here the output of the last line will be "There's no such thing" unless you pass in another string.

Back

Explain this code: file = File.open("master", "r+") p file.read file.rewind # try commenting out this line to see what happens! # can you guess why this happens? buffer = "" p file.read(23, buffer) p buffer file.close

Front

opening the file readwrite, printing the contents resetting the file pointer to the beginning printing the reading again, also into buffer, first 23 chars printing buffer

Back

Add code here to make this lambda one that increments any number passed to it by 1: Increment = lambda { }

Front

Increment = lambda { |i| i + 1}

Back

How do you forced the scoping on a constant or class to the topmost level?

Front

Prepend with ::

Back

How do you read the contents of the file into an array of lines?

Front

File#readlines lines = File.readlines("monk") p lines p lines[0]

Back

Explain this code: def demonstrate_block(number) yield(number) end puts demonstrate_block(1) { |number| number + 1 }

Front

After the parameter list, a block is passed to the method; the yield keyword within the method calls a single lambda that has been implicitly passed to a method without using the parameter list. This is the most common use case in Ruby.

Back

What three methods correlate most readily to STDIN, STDOUT, and STDERR?

Front

gets, puts, and warn

Back

What are the Ruby constants for your input, output, and error streams?

Front

STDIN, STDOUT, and STDERR

Back

What is the purpose of the global variables $stdin, $stdout, and $stderr?

Front

You can assign these variables to another IO object to pick up another IO stream than the default.

Back

How, in Ruby would you open a file called friend-list.txt in read-write mode at the beginning, inspect the file object, and print the contents? (obviously many ways)

Front

mode = "r+" file = File.open("friend-list.txt", mode) puts file.inspect puts file.read file.close

Back

Explain what Ruby modules are.

Front

Ruby modules allow you to create groups of methods. A module is not a class; you cannot have an "instance" of a module. Therefore modules only hold behavior, not state. Modules can be included in other classes, making its methods available to the instances of the including class.

Back

Explain what "namespacing" is with regard to modules.

Front

Namespaces let you bundle logically related objects together without fear of a naming collision. :: is a constant lookup operator. module Perimeter class Array def initialize @size = 400 end end end our_array = Perimeter::Array.new ruby_array = Array.new p our_array.class p ruby_array.class

Back