Kata Challenges Flashcards
Create a function that takes an integer as an argument and returns “Even” for even numbers or “Odd” for odd numbers.
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 can you return the number of a certain item in an array?
.count(item)
.select{ |item| item }.count
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
string. delete(‘!’)
- —
string. gsub(“!”, “”)
- —
string. tr(“!”, “”)
You get an array of numbers, return the sum of all of the positives ones.
def positive_sum(arr) arr.select{|x| x > 0}.reduce(0, :+) end ---- def positive_sum(arr) arr.select(&:positive?).inject(0,:+) end
From an array of numbers, return the longest element. If more than one have same size, return the first that appears.
def find_longest(arr) arr.max_by { |num| num.to_s.size } end
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
def remove_smallest(numbers) return [] if numbers.empty? numbers.delete_at(numbers.index(numbers.min)) return numbers end
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
def sequence_sum(begin_number, end_number, step)
(begin_number..end_number).step(step).reduce(0, :+)
end
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.
def longest_word(string_of_words)
string_of_words.split.sort_by(&:size).last
end
Given an array of strings, return the longest element
arr.max_by { |x| x.length }