Kata Challenges Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers.

A
def even_or_odd(number)
  number.even? ? "Even" : "Odd"
end
----
def even_or_odd(number)
  (number % 2 == 0) ? "Even" : "Odd"
end
----
def even_or_odd(number)
  ['Even', 'Odd'][number % 2]
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you return the number of a certain item in an array?

A

.count(item)

.select{ |item| item }.count

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

Write function RemoveExclamationMarks which removes all exclamation marks from a given string.

A

string. delete(‘!’)
- —
string. gsub(“!”, “”)
- —
string. tr(“!”, “”)

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

You get an array of numbers, return the sum of all of the positives ones.

A
def positive_sum(arr)
  arr.select{|x| x > 0}.reduce(0, :+)
end
----
def positive_sum(arr)
  arr.select(&:positive?).inject(0,:+)
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

From an array of numbers, return the longest element. If more than one have same size, return the first that appears.

A
def find_longest(arr)
  arr.max_by { |num| num.to_s.size }
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Given an array of integers, remove the smallest value. Do not mutate the original array/list. If there are multiple elements with the same value, remove the one with a lower index. If you get an empty array/list, return an empty array/list. Don’t change order

A
def remove_smallest(numbers)
  return [] if numbers.empty?
  numbers.delete_at(numbers.index(numbers.min))
  return numbers
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Your task is to make function, which returns the sum of a sequence of integers.

The sequence is defined by 3 non-negative values: begin, end, step.

If begin value is greater than the end, function should returns 0

A

def sequence_sum(begin_number, end_number, step)
(begin_number..end_number).step(step).reduce(0, :+)
end

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

When given a string of space separated words, return the word with the longest length. If there are multiple words with the longest length, return the last instance of the word with the longest length.

A

def longest_word(string_of_words)
string_of_words.split.sort_by(&:size).last
end

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

Given an array of strings, return the longest element

A

arr.max_by { |x| x.length }

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