Andres Bernal

Andres Bernal

Developer.

© 2019

Ruby Test

Ruby

๐Ÿ’Ž RUBY ๐Ÿ’Ž

Message

def hello()
	"hello" 
end

Return the Sum of Two Numbers


def addition(a, b)
	a + b

end

Return the Next Number from the Integer Passed

def addition(num)
	num + 1
end

Concatenate First and Last Name into One String

def concat_name(first_name, last_name)
	last_name + ", " + first_name
end

Is the Number Less than or Equal to Zero?

def less_than_or_equal_to_zero(num)
	!( num > 0)
end
#or
def less_than_or_equal_to_zero(num)
	num <= 0
end

Return the First Element in an Array

def get_first_value(arr)
	arr[0]
end

Return the Last Element in an Array

def get_last_item(arr)
	arr.pop()
end
#or
def get_last_item(arr)
	arr.[-1]
end

Re-Form The Word

def get_word(left, right)
	left.capitalize + right
end

Multiple of 100

def divisible(num)
	num % 100 == 0
end

Reverse an Array

def reverse(arr)
	arr.reverse
end

Area of a Triangle

def tri_area(base, height)
	(base * height) / 2
end

Compare Strings by Count of Characters

def tri_area(base, height)
	(base * height) / 2
end

Compare Strings by Count of Characters

def comp(str1, str2)
	str1.length === str2.length
end

Profitable Gamble

def profitable_gamble(prob, prize, pay)
	prob*prize-pay>0
end

Find the Smallest Number in an Array

  def find_smallest_num(arr)
	arr.min
  end

Difference of Max and Min Numbers in Array

def difference_max_min(arr)
	arr.max - arr.min
end

Find the Largest Number in an Array

def find_largest_num(nums)
	nums.max
end

Check if an Integer is Divisible By Five

def divisible_by_five(n)
	n % 5 === 0
end

Remove Duplicates from an Array

def remove_dups(arr)
	arr.uniq
end

Check String for Spaces

def has_spaces(str)
	!!(str =~ / /)
end

#or
def has_spaces(s)
	s.include?(' ')
end

Check if an Array Contains a Given Number

def check(arr, el)
	arr.include? el
end

Maximum Difference

def difference(nums)
	nums.max - nums.min
end

To the Power of _____

def calculate_exponent(num, exp)
	num**exp
end

Transform into an Array with No Duplicates

def set(arr)
	arr.uniq
end

Maximum Edge of a Triangle

def next_edge(side1, side2)
	(side1+side2)-1
end

String to Integer and Vice Versa

def to_int(str)
	str.to_i
end

def to_str(int)
	int.to_s
end

Purge and Organize

def unique_sort(arr)
	arr.sort.uniq
end

Sort Numbers in Ascending Order

def sort_nums_ascending(a)
	a.sort
end

Is the Word Singular or Plural?

def is_plural(word)
	word[-1] == 's'
end

Concatenating Two Integer Arrays

def concat(arr1, arr2)
	arr1 + arr2
end

Char-to-ASCII

def ctoa(char)
	char.ord
end

Is the Number Even or Odd?

def is_even_or_odd(n)
	n % 2 == 0 ? "even" : "odd"
end

Return the First and Last Elements in an Array

def first_last(a)
	[a.first,a.last]
end **Reverse the Order of a String**

def reverse(s)
	s.reverse
end

Palindrome?

def is_palindrome(str)
	str.reverse == str
end

Find the Total Number of Digits the Given Number Has

def find_digit_amount(num)
	num.to_s.size
end

Get Word Count

def count_words(str)
	str.split.size
end

Remove Nil from an Array

def remove_nil(a)
	a.compact
end

Find Unique Positive Numbers from Array

def unique_arr(a)
	a.select{|x| x > 0}.uniq
end

Find the Smallest and Biggest Numbers

def min_max(n)
	[n.min, n.max]
end

Limit a Numberโ€™s Value

def limit_number(*nums)
	nums.sort[1]
end

Between Words

def is_between(first, last, word)
	word.between? first, last
end

String or Integer?

def int_or_string(p)
	p.to_i == p ? "int" : "str"
end
#or
def int_or_string(param)
param.is_a?(Integer) ? 'int' : 'str'
end

Extract City Facts

city_facts({
  name: "Paris",
  population: "2,140,526",
  continent: "Europe"
}) โžž "Paris has a population of 2,140,526 and is situated in Europe"

city_facts({
  name: "Tokyo",
  population: "13,929,286",
  continent: "Asia"
}) โžž "Tokyo has a population of 13,929,286 and is situated in Asia"
def city_facts(city)
	"#{city[:name]} has a population of #{city[:population]} and is situated in #{city[:continent]}"
end

Nth Smallest Element

def nth_smallest(a, n)
  a.sort[n - 1]
end **Testing K^K == N?**

def k_to_k(n, k)
	k**k == n
end

Vowel Replacer

def replace_vowels(str, ch) 
	str.tr 'aeiou', ch
end

Word Endings

def add_ending(a, e)
	a.map{|x| x+e}
end
#or
def add_ending(arr, str)
  arr.map { |ele| ele << str }
end

Return the Remainder from Two Numbers

def remainder(x, y)
	x < 0 ? x : x % y
end **Calculate Determinant of a 2x2 Matrix**

def calc_determinant(matrix)
  (a, b), (c, d) = matrix
  a * d - b * c
end **Shuffle the Name**

def name_shuffle(s)
	s.split.reverse.join(' ')
end **Basic Statistics: Mean**

def mean(n)
	(n.reduce(:+) / n.size.to_f).round(1)
end
#or
   def mean(n)
	(n.reduce(:+).to_f / n.size).round(1)
end

Find the Index

def find_index(a, s) 
	a.index(s)
end

Case Insensitive Comparison

def match(s1, s2)
	s1.casecmp(s2)==0
end

Total Number of Unique Characters

def count_unique(s1, s2)
  (s1 + s2).chars.uniq.size
end

The 3 Programmers Problem

def programmers(*ns)
	ns.max - ns.min
end - **Generate N-Size Combinations from an Array**

  

  def combo(arr, n)
      arr.combination(n).to_a
    end

Is the String Empty?

def is_empty(s)
	s == ""
end

Alphabet Soup

def alphabet_soup(s)
	s.chars.sort.join
end **Check if a Number is a Palindrome**

def is_palindrome(n)
	n.to_s == n.to_s.reverse
end

Add, Subtract, Multiply or Divide?

def operation(n1, n2)
	n1+n2 == 24 ? "added" : n1-n2 == 24 ? "subtracted"
	: n1*n2 == 24 ? "multiplied" : n1/n2 == 24 ? "divided" : nil
end

Is the Number Symmetrical?

def is_symetrical?(i)
	i == i.to_s.reverse.to_i
end **Array from Comma-Delimited String**

def to_array(s)
	s.split(', ')
end **Next Element in Arithmetic Sequence**

  def next_element(arr)
	arr.last + (arr[1] - arr[0])
end

Typing Game

def correct_stream(user, correct)
	user.zip(correct).map{|x, y| x==y}.map{|x| x==true ? 1 : -1}
end
#or
def correct_stream(user, correct)
  user.zip(correct).map { |a, b| a == b ? 1 : 	-1 }
end

Even Odd Partition

def even_odd_partition(a)
  a = a.group_by(&:even?)
  [a[true] || [], a[false] || []]
end
#or

def even_odd_partition(arr)
arr.partition(&:even?)
end

#or
def even_odd_partition(arr)
arr.partition{|x| x.even?}
end

Hashes and Pluses

def hash_plus_count(str)
	[str.count("#"),str.count("+")]
end

#or
def hash_plus_count(s)
      g = {'#' => [], '+' => []}.merge(s.chars.group_by(&:to_s))
      [g['#'].size, g['+'].size]
end
def hash_plus_count(str)
	[str.scan("#").size, str.scan("+").size]
end

Eliminate Odd Numbers within an Array

def no_odds(arr)
	arr.select(&:even?)
end **Sort an Array by String Length**

def sort_by_length(arr)
	arr.sort_by(&:length)
end

Return the Four Letter Strings

def is_four_letters(arr)
	arr.select { |str| str.length == 4 }
end
  
#or
   def is_four_letters(arr)
	arr.select {|str| str.length == 4}
    end    

Check if String Ending Matches Second String

def check_ending(str1, str2)
	str1[-str2.length..-1] == str2
end

Product Divisible by Sum?

def divisible(arr)
  0 == arr.reduce(:*) % arr.reduce(:+)
end

#or
def divisible(arr)
	(arr.inject(:*) % arr.inject(:+)).zero?
end

Fix the Spacing

def correct_spacing(s)
	s.split.join(' ')
end

#or
def correct_spacing(sentence)
sentence.strip.split.join(' ')
end

Get the File Extension

def get_extension(arr)
	arr.collect do |file|
		file.split('.').pop
	end
end

def get_extension(a)
  a.map { |f| File.extname(f)[1..-1] }
end
# or

def get_extension(arr)
arr.map { |el| el.split('.')[-1] }
end

Return the Factorial

def factorial(int)
	return 1 if int == 0
	int * factorial(int-1)
end
#or

def factorial(int)
(1..int).inject(:*)
end

Slice of Pie

def equal_slices(total, people, each)
	people * each <= total
end

Odd Up, Even Down

def transform(a)
	a.map{|x|x % 2 == 0 ? x-1 : x+1}
end

def transform(a)
  a.map { |a| (a & 1) - (~a & 1) + a }
end

Capitalize by ASCII

def ascii_capitalize(s) 
	s.split('').map{|x| x.ord % 2 === 0 ? x.upcase : x.downcase }.join('')
end

#or
def ascii_capitalize(s)
  s.map { |c| c.ord & 1 == 1 ? c.downcase : 	c.upcase }
end

class String
  def map
    self.each_char.reduce('') { |s, c| s << yield(c) }
  end
end

Check if Number is within a Given Range

def is_in_range(num, range)
  (range[:min]..range[:max]).include?(num)
end

#or
def is_in_range(num, range)
return num >= range[:min] && num <= range[:max]
end **Stretched Words**

def unstretch(w)
	w.squeeze
end
#or
def unstretch(word)
	word.chars.chunk_while { |c1, c2| c1 == c2 }.to_a.map(&:uniq).join
end

Multiply by Length

def multiply_by_length(arr)
	arr.map do |n|
		n * arr.length
	end
end
#or
def multiply_by_length(arr)
arr.map{|x| x * arr.length}
end

Find ASCII Charcode of Inverse Case Character

def counterpart_char_code(char)
	char.swapcase.ord
end

def counterpart_char_code(c)
	c == c.upcase ? c.downcase.ord : c.upcase.ord
end

Recursion: Sum

def sum(n)
	(0..n).reduce{|x,a|x+a}
end
#or
def sum(n)
n == 1 ? n : n + sum(n-1);
end **Amplify the Multiples of 4**

def amplify(n)
	(1..n).map{|x| x % 4 == 0 ? x * 10 : x}
end
#or
def amplify(num)
  (1..num).map { |n| n % 4 == 0 ? n * 10 : n}
end **Missing Third Angle**

def missing_angle(angle1, angle2)
	180 - angle1 - angle2 < 90 ? "acute" : 180 - angle1 - angle2 > 90 ? "obtuse" : "right"
end **Fix the Error: Vowel Edition** ```

def removeVowels(str)
  return str.sub(/[aeiou]/i, '')
end

```

Repeating Letters N Times

def repeat(s, n)
  s.chars.map { |c| c * n }.join
end

Fix the Error: Vowel Edition

def removeVowels(s)
	s.gsub(/[aeiou]/i, '')
end

Remove Every Vowel from a String

def remove_vowels(str)
	str.delete("aeiouAEIOU")
end

Check if the Same Case

def same_case(s)
	s == s.downcase || s == s.upcase
end

Convert Number to Corresponding Month Name

def month_name(num)
	Date::MONTHNAMES[num]
end

def month_name(num)
	hash = {
		1 => 'January',
		2 => 'February',
		3 => 'March',
		4 => 'April',
		5 => 'May',
		6 => 'June',
		7 => 'July',
		8 => 'August',
		9 => 'September',
		10 => 'October',
		11 => 'November',
		12 => 'December'
		}
	hash[num]
end

GCD and LCM ( Part 1)

def gcd(a, b)
	a.gcd(b)
end
#or
def gcd(a, b)
	(1..[a, b].sort.first).to_a.reverse.each { |f| return f if a % f == 0 && b % f == 0 }
end **Is it Time for Milk and Cookies?**

def timeForMilkAndCookies(d)
  d.month == 12 && d.day == 24
end

Even Number Generator

def find_even_nums(num)
	(2..num).step(2).to_a
end **Convert to Decimal Notation**

def convert_to_decimal(p)
	p.map{|x| x.to_f/100 }
end

Generate a Countdown of Numbers in an Array

def countdown(s)
	[*0..s].reverse
end

Numbers to Arrays and Vice Versa

def to_array(num)
	num.to_s.chars.map(&:to_i)
end

def to_number(arr)
  arr.join.to_i	
end **Mirror Array**

def mirror(a)
	a + a.reverse[1..5]
end **GCD and LCM (Part 2)**

def lcm(a, b)
	a.lcm(b)
end

def lcm(a, b)
	([a,b].sort.last..a * b).to_a.each { |m| return m if m % a == 0 && m % b == 0 }
end

Is the Average of All Elements a Whole Number?

def is_avg_whole?(arr)
	arr.inject(:+) % arr.size == 0
end

Add up the Numbers from a Single Number

def add_up(n)
	(n*(n+1))/2
end

Say Hello to Guests

def greet_people(names)
	names.map{|x| "Hello " + x}.join(', ')
end

H4ck3r Sp34k

def hacker_speak(str)
	str.tr 'aeios', '43105'
end

def hacker_speak(s)
	s.gsub(/[aeios]/, 'a' => 4, 'e' => 3, 'i'=> 1, 'o' => 0, 's' => 5)
end

Pi to N Decimal Places

def my_pi(n)
	Math::PI.round n
end

Capitalize the Names

def cap_me(arr)
	arr.map &:capitalize
end

Count Instances of a Character in a String

def char_count(str1, str2)
	str2.count str1
end

Semantic Versioning

def retrieve_major(s)
	s.split('.')[0]
end

def retrieve_minor(s)
	s.split('.')[1]
end

def retrieve_patch(s)
	s.split('.')[2]
end

Flip the Boolean

def reverse(bool)
	!!bool == bool ? !bool : "boolean expected"
end

Is the Object Empty?

def is_empty(o)
	o.empty?
end **Filter out Strings from an Array**

def filter_list(a)
	a.select{|b| b.is_a? Integer}
end

def filter_list(arr)
	arr.select{|x| x != x.to_s }
end **Calculate the Mean**

def mean(arr)
	(arr.reduce(:+).to_f / arr.size).round 2
end

How Many Vowels?

def count_vowels(s)
	s.count("aeiou")
end

Mean of All Digits

def mean(num)
	nums = num.abs.to_s.chars.map(&:to_i)
	nums.reduce(:+)/nums.length
end