Fundamentals Flashcards

1
Q

What does .include? return

A

if string_to_check.include? “substring”

It evaluates to true if it finds what it’s looking for and false otherwise.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

As a general rule, Ruby methods that end with ? evaluate to what?

A

As a general rule, Ruby methods that end with ? evaluate to the boolean values true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain what gsub does and what inputs it takes

A

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*”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between 1..10 and 1…10

A

Two dots includes last number

Three dots does not include last number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are two ways to create a hash?

A
h = Hash.new
h["keyname"] = "valuename"

h = { “keyname” => “valuename”}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What input does split take and what does it return?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you set a default value for a Hash?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are splat arguments?

A

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.”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the combined comparison operator and how does it work?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you sort an array called books in descending order?

A

books.sort! { |a, b| b <=> a}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What does rev=false mean in this method?

def alphabetize(arr, rev=false)

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the only two non-true values in Ruby?

A

false

nil

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What happens if you try to access a key that doesn’t exist, though?

A

In many languages, you’ll get an error of some kind. Not so in Ruby: you’ll instead get the special value nil.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does nil mean

A

It means “nothing at all”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are 3 reasons why Symbols make good hash keys?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What method do you use to iterate over only Hash keys and what method do you use to iterate over only Hash values?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the method string.strip do?

A

Returns a copy of str with leading and trailing whitespace removed.

” hello “.strip #=> “hello”
“\tgoodbye\r\n”.strip #=> “goodbye”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

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!”

A

puts “It’s true!” if true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you write a ternary conditional expression?

A

boolean ? Do this if true: Do this if false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How do you write a ternary conditional expression?

A

boolean ? Do this if true: Do this if false

22
Q

Write a case statement called language and set each case to a programming language and set the default to “I don’t know!”

A
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
23
Q

What is the Implicit Return in Ruby?

A

Ruby’s methods will return the result of the last evaluated expression.

24
Q

What is short-circuit evaluation?

A

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.

25
Q

What does the method .respond_to? do

A

.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.

26
Q

What does the .next method do?

A

.next will return the integer immediately following the integer it’s called on, meaning 4.next will return 5.

27
Q

How do you use the concatenation operator (also known as “the shovel”)

A

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"
28
Q

What is the conditional assignment operator?

A

||=

Assign a value to a variable that has not been assigned yet

29
Q

Why do some methods accept a block and others don’t?

A

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!” }

30
Q

What does fdiv() do?

A

Returns the floating point result of dividing fix by numeric.

  1. fdiv(13731) #=> 47.6528293642124
  2. fdiv(13731.24) #=> 47.6519964693647
31
Q

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!

A
def double(par)
   yield(par) 
end

double(2) {|n| n*2}

32
Q

What does the chomp method do?

A

The chomp method is called on a string and removes any newlines at the end of the string.

33
Q

Why do we need to put chomp after getting a user input with gets?

A

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.

34
Q

Write a program that puts an array backward.

A
arr = ["Racecars", "Lasers", "Aeroplanes"]
idx = arr.length - 1
while idx >= 0
  puts(cool_things[idx])
  idx = idx - 1
end
35
Q

What does the unshift method do?

A

Adds items to the start of the array.

36
Q

What does shift do?

A

Removes items from the front of the array

37
Q
# 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

A

def factorial(n)
if n < 0
return nil
end

result = 1
while n > 0
result = result * n

n -= 1   end

return result
end

38
Q

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

A

def factorial(n)
if n < 0
return nil
end

result = 1
while n > 0
result = result * n

n -= 1   end

return result
end

39
Q
# 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`.
A
def sum_nums(num)
  sum = 0
  count = 0 
  while count <= num
    sum = sum + count
    count = count + 1
  end 
  return sum
end
40
Q

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.

A
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

41
Q
# 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.
A
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
42
Q
# 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”

A
def scramble_string(string, positions)
  i = 0 
  value = ""
  while i < positions.length 
   value = value+string[positions[i]]
   i+=1
 end
 return value
end
43
Q
# Write a method that takes in an integer (greater than one) and
# returns true if it is prime; otherwise return false.
A
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

44
Q
# 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

A
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
45
Q

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.
A
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
46
Q
# 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.
A
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 &amp;&amp; number2 % i == 0 
      return i 
      break
    end 
    i-=1 
  end 
end
47
Q

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.

A
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
48
Q

Write a function lucky_sevens?(numbers), which takes in an array of integers and returns true if any three consecutive elements sum to 7.

A
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
49
Q

Write a function oddball_sum(numbers), which takes in an array of integers and returns the sum of all the odd elements.

A
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
50
Q

What does the shuffle method do?

A

To shuffle an array in random order, use the shuffle method:

[1, 2, 3].shuffle
# => [2, 1, 3]
51
Q

How do you get a random element from an array?

A

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