Fundamentals Flashcards
What does .include? return
if string_to_check.include? “substring”
It evaluates to true if it finds what it’s looking for and false otherwise.
As a general rule, Ruby methods that end with ? evaluate to what?
As a general rule, Ruby methods that end with ? evaluate to the boolean values true or false.
Explain what gsub does and what inputs it takes
gsub(pattern, replacement) → new_str click to toggle source
gsub(pattern, hash) → new_str
gsub(pattern) {|match| block } → new_str
gsub(pattern) → enumerator
Returns a copy of str with the all occurrences of pattern substituted for the second argument. The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. ‘\d’ will match a backlash followed by ‘d’, instead of a digit.
If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form \d, where d is a group number, or \k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as $&, will not refer to the current match.
If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $’ will be set appropriately. The value returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
When neither a block nor a second argument is supplied, an Enumerator is returned.
“hello”.gsub(/[aeiou]/, ‘’) #=> “hll”
“hello”.gsub(/([aeiou])/, ‘’) #=> “hll”
“hello”.gsub(/./) {|s| s.ord.to_s + ‘ ‘} #=> “104 101 108 108 111 “
“hello”.gsub(/(?[aeiou])/, ‘{\k}’) #=> “h{e}ll{o}”
‘hello’.gsub(/[eo]/, ‘e’ => 3, ‘o’ => ‘’) #=> “h3ll*”
What is the difference between 1..10 and 1…10
Two dots includes last number
Three dots does not include last number
What are two ways to create a hash?
h = Hash.new h["keyname"] = "valuename"
h = { “keyname” => “valuename”}
What input does split take and what does it return?
Divides str into substrings based on a delimiter, returning an array of these substrings.
If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.
If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.
If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.
If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.
When the input str is empty an empty Array is returned as the string is considered to have no fields to split.
” now’s the time”.split #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(‘ ‘) #=> [“now’s”, “the”, “time”]
“ now’s the time”.split(/ /) #=> [””, “now’s”, “”, “the”, “time”]
“1, 2.34,56, 7”.split(%r{,\s}) #=> [“1”, “2.34”, “56”, “7”]
“hello”.split(//) #=> [“h”, “e”, “l”, “l”, “o”]
“hello”.split(//, 3) #=> [“h”, “e”, “llo”]
“hi mom”.split(%r{\s}) #=> [“h”, “i”, “m”, “o”, “m”]
“mellow yellow”.split(“ello”) #=> [“m”, “w y”, “w”]
“1,2,,3,4,,”.split(‘,’) #=> [“1”, “2”, “”, “3”, “4”]
“1,2,,3,4,,”.split(‘,’, 4) #=> [“1”, “2”, “”, “3,4,,”]
“1,2,,3,4,,”.split(‘,’, -4) #=> [“1”, “2”, “”, “3”, “4”, “”, “”]
”“.split(‘,’, -1) #=> []
How do you set a default value for a Hash?
If you have a hash with a default value, and you try to access a non-existent key, you get that default value.
h = Hash.new(“nothing here”)
puts h # {}
puts h["kitty"] # nothing here
Write a program that takes a user input
Splits the input into separate words
Add those words to a Hash
Puts the word and the amount of times it appears
puts ‘input’
text = gets.chomp
words = text.split(“ “)
frequencies = Hash.new(0)
words.each do |word|
frequencies[word] += 1
end
frequencies = frequencies.sort_by do |word, count|
count
end
frequencies.reverse!
frequencies.each do |key, value|
puts “#{key} #{value}”
end
What are splat arguments?
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.”
What is the combined comparison operator and how does it work?
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.
How would you sort an array called books in descending order?
books.sort! { |a, b| b <=> a}
What does rev=false mean in this method?
def alphabetize(arr, rev=false)
What this does is tell Ruby that alphabetize has a second parameter, rev (for “reverse”) that will default to false if the user doesn’t type in two arguments.
What are the only two non-true values in Ruby?
false
nil
What happens if you try to access a key that doesn’t exist, though?
In many languages, you’ll get an error of some kind. Not so in Ruby: you’ll instead get the special value nil.
What does nil mean
It means “nothing at all”
What are 3 reasons why Symbols make good hash keys?
They’re immutable, meaning they can’t be changed once they’re created;
Only one copy of any symbol exists at a given time, so they save memory;
Symbol-as-keys are faster than strings-as-keys because of the above two reasons.
What method do you use to iterate over only Hash keys and what method do you use to iterate over only Hash values?
Ruby includes two hash methods, .each_key and .each_value, that do exactly what you’d expect:
my_hash = { one: 1, two: 2, three: 3 }
my_hash.each_key { |k| print k, " " } # ==> one two three
my_hash.each_value { |v| print v, " " } # ==> 1 2 3
What does the method string.strip do?
Returns a copy of str with leading and trailing whitespace removed.
” hello “.strip #=> “hello”
“\tgoodbye\r\n”.strip #=> “goodbye”
Which line is the correct way to write an if statement in one line using Ruby?
puts “It’s true!” if true
OR
if true puts “It’s true!”
puts “It’s true!” if true
How do you write a ternary conditional expression?
boolean ? Do this if true: Do this if false
How do you write a ternary conditional expression?
boolean ? Do this if true: Do this if false
Write a case statement called language and set each case to a programming language and set the default to “I don’t know!”
case language when "JS" puts "Websites!" when "Python" puts "Science!" when "Ruby" puts "Web apps!" else puts "I don't know!" end
OR
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
What is the Implicit Return in Ruby?
Ruby’s methods will return the result of the last evaluated expression.
What is short-circuit evaluation?
That means that Ruby doesn’t look at both expressions unless it has to; if it sees
false && true
it stops reading as soon as it sees && because it knows false && anything must be false.
What does the method .respond_to? do
.respond_to? takes a symbol and returns true if an object can receive that method and false otherwise. For example,
[1, 2, 3].respond_to?(:push)
would return true, since you can call .push on an array object. However,
[1, 2, 3].respond_to?(:to_sym)
would return false, since you can’t turn an array into a symbol.
What does the .next method do?
.next will return the integer immediately following the integer it’s called on, meaning 4.next will return 5.
How do you use the concatenation operator (also known as “the shovel”)
Instead of typing out the .push method name, you can simply use < [1, 2, 3, 4]
Good news: it also works on strings! You can do:
"Yukihiro " << "Matsumoto" # ==> "Yukihiro Matsumoto"
What is the conditional assignment operator?
||=
Assign a value to a variable that has not been assigned yet
Why do some methods accept a block and others don’t?
It’s because methods that accept blocks have a way of transferring control from the calling method to the block and back again. We can build this into the methods we define by using the yield keyword.
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!” }
What does fdiv() do?
Returns the floating point result of dividing fix by numeric.
- fdiv(13731) #=> 47.6528293642124
- fdiv(13731.24) #=> 47.6519964693647
Define your own method, double, that accepts a single parameter and yields to a block. Then call it with a block that multiplies the number parameter by 2. You can double any number you like!
def double(par) yield(par) end
double(2) {|n| n*2}
What does the chomp method do?
The chomp method is called on a string and removes any newlines at the end of the string.
Why do we need to put chomp after getting a user input with gets?
If I run this program and type in “Ned”, followed by enter, the program will output:
Hello Ned
!
The “!” will be placed on the following line. That’s because Ruby reads the characters “N”, “e”, “d”, and enter. Because it reads the enter character (technically called the newline character), there’s a newline after the “d” but before the “!” in the output.
The chomp method is called on a string and removes any newlines at the end of the string.
Write a program that puts an array backward.
arr = ["Racecars", "Lasers", "Aeroplanes"] idx = arr.length - 1 while idx >= 0 puts(cool_things[idx]) idx = idx - 1 end
What does the unshift method do?
Adds items to the start of the array.
What does shift do?
Removes items from the front of the array
# Write a method that takes an integer `n` in; it should return # n*(n-1)*(n-2)*...*2*1. Assume n >= 0. # # As a special case, `factorial(0) == 1`
https://repl.it/Br5o/0
def factorial(n)
if n < 0
return nil
end
result = 1
while n > 0
result = result * n
n -= 1 end
return result
end
Refactor this code
def factorial(n) total = 1 count = n
if n == 0 || n == 1 total = 1 elsif n > 1 while count > 0 total = total * count count = count - 1 end end
return total
end
def factorial(n)
if n < 0
return nil
end
result = 1
while n > 0
result = result * n
n -= 1 end
return result
end
# Write a method that takes in an integer `num` and returns the sum of # all integers between zero and num, up to and including `num`.
def sum_nums(num) sum = 0 count = 0
while count <= num sum = sum + count count = count + 1 end return sum end
Write a method that takes a string in and returns true if the letter “z” appears within three letters after an “a”. You may assume that the string contains only lowercase letters.
def nearby_az(string) i = 0
while i < string.length - 1 if string[i] == 'a' itwo = 1 while itwo <= 3 if string[i +itwo] == 'z' return true end itwo+= 1 end end i+=1 end
return false
end
# Write a method that takes in a string of lowercase letters and # spaces, producing a new string that capitalizes the first letter of # each word.
def capitalize_words(string) string_array = string.split(" ") i = 0 while i < string_array.length string_array[i][0] = string_array[i][0].upcase i +=1 end return string_array.join(" ") end
# Write a method that takes in a string and an array of indices in the # string. Produce a new string, which contains letters from the input # string in the order specified by the indices of the array of indices.
scramble_string(“abcd”, [3, 1, 2, 0]) == “dbca”
def scramble_string(string, positions) i = 0 value = "" while i < positions.length value = value+string[positions[i]] i+=1 end return value end
# Write a method that takes in an integer (greater than one) and # returns true if it is prime; otherwise return false.
def is_prime?(number) if number <= 1 # only numbers > 1 can be prime. return false end
idx = 2 while idx < number if (number % idx) == 0 return false end
idx += 1 end
return true
end
# Write a method that returns the `n`th prime number. Recall that only # numbers greater than 1 can be prime. # # Difficulty: medium.
Assume there is an is_prime?
method that tells you if a number is prime or not
def nth_prime(n) prime_num = 0
i = 2 while true if is_prime?(i) prime_num += 1 if prime_num == n return i end end
i += 1 end end
Assume there is a method called palindrome which is already created that tells you if an input is a palindrome in a boolean value
# Write a method that takes in a string of lowercase letters (no # uppercase letters, no repeats). Consider the *substrings* of the # string: consecutive sequences of letters contained inside the string. # Find the longest such string of letters that is a palindrome. # # Note that the entire string may itself be a palindrome.
def longest_palindrome(string) i = 0 longest = "" while i < string.length j = i+1 while j <= string.length if palindrome?(string.slice(i, j)) check = string.slice(i, j) if check.length > longest.length longest = check end end j+=1 end i+=1 end return longest end
# Write a method that takes in two numbers. Return the greatest # integer that evenly divides both numbers. You may wish to use the # `%` modulo operation.
def greatest_common_factor(number1, number2) limit = nil if number1 > number2 limit = number1 else limit = number2 end
i = limit while i >= 1 if number1 % i == 0 && number2 % i == 0 return i break end i-=1 end end
Write a method that finds if an array of numbers has a pair that sums to zero. Be careful of the case of zero; there need to be two zeroes in the array to make a pair that sums to zero.
arr = [1,0,0] def add_zero?(arr) arr.each do |n| i = 0 while i < arr.length if n + arr[i] == 0 return true end i +=1 end end return false end
Write a function lucky_sevens?(numbers), which takes in an array of integers and returns true if any three consecutive elements sum to 7.
def lucky_sevens?(numbers) i = 0 while i < numbers.length - 2 added = numbers[i].to_i + numbers[i+1].to_i + numbers[i+2].to_i if added == 7 return true end i+=1 end return false end
Write a function oddball_sum(numbers), which takes in an array of integers and returns the sum of all the odd elements.
def oddball_sum(numbers) odd_balls = [] numbers.each do |num| if num == 0 odd_balls.push(num) elsif num % 2 != 0 odd_balls.push(num) end end puts odd_balls.reduce(:+) end
What does the shuffle method do?
To shuffle an array in random order, use the shuffle method:
[1, 2, 3].shuffle # => [2, 1, 3]
How do you get a random element from an array?
The sample method selects an element at random from the array where each element has equal probability of being selected. This does not alter the array.
die = [1,2,3,4,5,6] roll1 = die.sample roll2 = die.sample