Multiply - first ruby code ever. This code does not execute properly. Try to figure out why
def multiply(a b) return a * b end
def multiply(a, b) return a * b end
Even or odd - 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)
def even_or_odd(number) if number % 2 == 0 return "Even" else return "Odd" end end
Opposite number - Very simple, given a number, find its opposite.
def opposite
end
def opposite(num) num * -1 end
Convert boolean values to strings 'Yes' or 'No' - Complete the method that takes a boolean value and return a "Yes" string for true, or a "No" string for false.
def bool_to_word bool
end
def bool_to_word bool bool ? "Yes" : "No" end
Convert a Booleans to a string - mplement a function which convert the given boolean value into its string representation.
def boolean_to_string(b) return end
def boolean_to_string(b) return b.to_s end
Reversed Strings - Complete the solution so that it reverses the string passed into it.
def solution(str)
end
def solution(str) str.reverse end
Reversing Words in a String - You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
As the input may have trailing spaces, you will also need to ignore unneccesary whitespace.
Example (Input --> Output)
"Hello World" --> "World Hello" "Hi There." --> "There. Hi"
def reverse(string)
end
def reverse(string) string.split(' ').reverse.join(' ') end
Convert a string to a Number! - We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.
def string_to_number(s)
end
def string_to_number(s) s.to_i end
Diemvowel Trolls - Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".
Note: for this kata y isn't considered a vowel.
def disemvowel(str)
end
def disemvowel(str) str.gsub(/[aeiou]/i, '') end
Messi Goals Function - Messi is a soccer player with goals in three leagues:
LaLiga Copa del Rey Champions Complete the function to return his total number of goals in all three leagues.
def goals (laLigaGoals, copaDelReyGoals, championsLeagueGoals)
end
def goals (laLigaGoals, copaDelReyGoals, championsLeagueGoals) laLigaGoals + copaDelReyGoals + championsLeagueGoals end
def goals(*goals) goals.sum end
Grasshopper - Basic function fixer - I created this function to add five to any number that was passed in to it and return the new value. It doesn't throw any errors but it returns the wrong number.
Can you help me fix the function?
def addFive(num) res = num + 5 return num end
def addFive(num) res = num + 5 return res end
def addFive(num) num + 5 end
Grasshopper - function syntax debugging - A student was working on a function and made some syntax mistakes while coding. Help them find their mistakes and fix them.
def main[verb, noun] return ; verb + noun }
def main(verb, noun) return verb + noun end
Grasshopper debug sayHello - The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!
def say_hello(name) "Hello" end
def say_hello(name) "Hello," + ' ' + name end
Grasshopper If-else syntax debug - While making a game, your partner, Greg, decided to create a function to check if the user is still alive called checkAlive/CheckAlive/check_alive. Unfortunately, Greg made some errors while creating the function.
checkAlive/CheckAlive/check_alive should return true if the player's health is greater than 0 or false if it is 0 or below.
The function receives one parameter health which will always be a whole number between -10 and 10.
def check_alive(health) if () health < 0 return False else return True end end
def check_alive(health) if health > 0 return true else return false end end
def check_alive(health) health.positive? end
def check_alive(health) health > 0 end
Grasshopper - Variable Assignment Debug - Fix the variables assigments so that this code stores the string 'devLab' in the variable name.
a == "dev" b == "Lab"
name == a + b
a = "dev" b = "Lab"
name = a + b
Basic variable assignment - This code should store "codewa.rs" as a variable called name but it's not working. Can you figure out why?
a == "code" b == "wa.rs" name == a + b
a = "code" b = "wa.rs" name = a + b
Training JS #7: if..else and ternary operator - Complete function saleHotdogs/SaleHotDogs/sale_hotdogs, function accept 1 parameters:n, n is the number of customers to buy hotdogs, different numbers have different prices (refer to the following table), return a number that the customer need to pay how much money.
def sale_hotdogs(n)
end
def sale_hotdogs(n) if n < 5 return n100 elsif n >= 5 && n < 10 return n95 elsif n >= 10 return n*90 end end
def sale_hotdogs(n) n * (n < 5 ? 100 : n < 10 ? 95 : 90) end
Remove first and last character - It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
def remove_char(s) end
def remove_char(s) s[1...-1] end
Remove String Spaces - Simple, remove the spaces from the string, then return the resultant string.
def no_space(s) end
def no_space(x) x.delete(' ') end
def no_space(x) x.gsub(' ', '') end
Function 1 hello world - Make a simple function called greet that returns the most-famous "hello world!".
def greet string = "hello world!" end
Jennys secret message - Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake.
Can you help her?
def greet(name) return "Hello, #{name}!" eturn "Hello, my love!" if name == "Johnny" end
def greet(name) name == "Johnny" ? "Hello, my love!" : "Hello, #{name}!" end
Reversed Words - Complete the solution so that it reverses all of the words within the string passed in.
def solution(sentence) end
def solution(sentence) sentence.split(' ').reverse.join(' ') end
Convert a number to a string - We need a function that can transform a number into a string.
What ways of achieving this do you know?
def number_to_string(num) end
def number_to_string(num) num.to_s end
Convert a string to an array - Write a function to split a string and convert it into an array of words
def string_to_array(string) end
def string_to_array(string) string.split end
Sum Arrays - Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.
def sum(numbers) end
def sum(numbers) numbers.sum end
Araay plus array - I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help.
def array_plus_array(arr1, arr2) arr1 + arr2. end
def array_plus_array(arr1, arr2) arr1.sum + arr2.sum end
def array_plus_array(arr1, arr2) (arr1 + arr2).reduce(:+) end
MakeUpperCase - Write a function which converts the input string to uppercase.
def make_upper_case(str) end
def make_upper_case(str) str.upcase end
You only need one - Beginner - You will be given an array a and a value x. All you need to do is check whether the provided array contains the value.
Array can contain numbers or strings. X can be either.
Return true if the array contains the value, false if not.
def check(arr,element) end
def check(arr,element) arr.include?(element) ? true : false end
Remove exclamation marks - Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
def remove_exclamation_marks(s) end
def remove_exclamation_marks(s) s.delete("!") end
Function 3 - multiplying two numbers - Implement a function which multiplies two numbers. (no starting code given)
def multiply (a,b) a * b end
Grasshopper - Messi Goals - Use variables to find the sum of the goals Messi scored in 3 competitions
la_liga_goals = 43 champions_league_goals = 10 copa_del_rey_goals = 5
puts total_goals
la_liga_goals = 43 champions_league_goals = 10 copa_del_rey_goals = 5 total_goals = la_liga_goals + champions_league_goals + copa_del_rey_goals
puts total_goals
Grasshopper - Messi goals function - laLigaGoals, copaDelReyGoals, championsLeagueGoals
def goals (laLigaGoals, copaDelReyGoals, championsLeagueGoals) end
def goals (laLigaGoals, copaDelReyGoals, championsLeagueGoals) laLigaGoals + copaDelReyGoals + championsLeagueGoals end
def goals(*goals) goals.sum end
Grasshopper - Bug Squashing - You are creating a text-based terminal version of your favorite board game. In the board game, each turn has six steps that must happen in this order: roll the dice, move, combat, get coins, buy more health, and print status.
You are using a library that already has the functions below. Create a function named main that calls the functions in the proper order.
combat
buy_health
get_coins
print_status
roll_dice
move
health = 100 position = 0 coins = 0
def main () roll_dice() move() combat() get_coins() buy_health() print_status() end
101 dalmatians - Your friend has been out shopping for puppies (what a time to be alive!)... He arrives back with multiple dogs, and you simply do not know how to respond!
By repairing the function provided, you will find out exactly how you should respond, depending on the number of dogs he has.
The number of dogs will always be a number and there will always be at least 1 dog.
def how_many_dalmatians(n) dogs ["Hardly any", "More than a handful!", "Woah that's a lot of dogs!", "101 DALMATIONS!!!"];
respond = number <= 10 ? dogs[0] (number <= 50 ? dogs[1] : (number = 101 dogs[3] : dogs[2]
return respond end
def how_many_dalmatians(n) dogs = ["Hardly any", "More than a handful!", "Woah that's a lot of dogs!", "101 DALMATIONS!!!"];
respond = n <= 10 ? dogs[0] : n <= 50 ? dogs[1] : n <= 100 ? dogs[2] : dogs[3]
return respond end
def how_many_dalmatians(n) case when n <= 10 then "Hardly any" when n <= 50 then "More than a handful!" when n == 101 then "101 DALMATIONS!!!" else "Woah that's a lot of dogs!" end end
Grasshopper - Personalized Message - Create a function that gives a personalized greeting. This function takes two parameters: name and owner.
Use conditionals to return the proper message:
case return name equals owner 'Hello boss' otherwise 'Hello guest'
def greet(name,owner) end
def greet(name,owner) name == owner ? 'Hello boss' : 'Hello guest' end
Person Class Bug - The following code was thought to be working properly, however when the code tries to access the age of the person instance it fails.
person = Person.new('Yukihiro', 'Matsumoto', 47) puts person.full_name puts person.age For this exercise you need to fix the code so that it works correctly.
class Person def initialize(firstName, lastName, age) @firstName = firstName @lastName = lastName @age = age end
def full_name "#{@firstName} #{@lastName}" end end
class Person attr_accessor :age def initialize(firstName, lastName, age) @firstName = firstName @lastName = lastName @age = age end
def full_name "#{@firstName} #{@lastName}" end end
My head is at the wrong end! - You're at the zoo... all the meerkats look weird. Something has gone terribly wrong - someone has gone and switched their heads and tails around!
Save the animals by switching them back. You will be given an array which will have three values (tail, body, head). It is your job to re-arrange the array so that the animal is the right way round (head, body, tail).
Same goes for all the other arrays/lists that you will get in the tests: you have to change the element positions with the same exact logics
def fix_the_meerkat(arr) end
def fix_the_meerkat(arr) arr.reverse end
Thinkful - Logic Drills: Traffic Light - You're writing code to control your town's traffic lights. You need a function to handle each change from green, to yellow, to red, and then to green again.
Complete the function that takes a string as an argument representing the current state of the light and returns a string representing the state the light should change to.
For example, update_light('green') should return 'yellow'.
def_update(current) end
def update_light(current) if current == 'green' return 'yellow' elsif current == 'yellow' return 'red' else return 'green' end end
def update_light(current) {"green" => "yellow", "yellow" => "red", "red" => "green"}[current] end
Your task is to create functionisDivideBy (or is_divide_by) to check if an integer number is divisible by each out of two arguments.
def is_divide_by(number, a, b) end
def is_divide_by(number, a, b) number % a == 0 && number % b == 0 ? true : false end
Name Shuffler - Write a function that returns a string in which firstname is swapped with last name.
name_shuffler('john McClane'); => "McClane john"
def name_shuffler(str) end
def name_shuffler(str) str.split.reverse.join(' ') end
Find numbers which are divisible by the given number - Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of numbers and the second is the divisor.
def divisible_by(numbers, divisor) end
def divisible_by(numbers, divisor) numbers.select { |n| n % divisor == 0 } end
Training JS #7: if else and ternary operator - Complete function saleHotdogs/SaleHotDogs/sale_hotdogs, function accept 1 parameters:n, n is the number of customers to buy hotdogs, different numbers have different prices (refer to the following table), return a number that the customer need to pay how much money.
+---------------+-------------+ | numbers n | price(cents)| +---------------+-------------+ |n<5 | 100 | +---------------+-------------+ |n>=5 and n<10 | 95 | +---------------+-------------+ |n>=10 | 90 | +---------------+-------------+
def sale_hotdogs(n) end
def sale_hotdogs(n) n < 5 ? n * 100 : n >= 5 && n < 10 ? n * 95 : n * 90 end
def sale_hotdogs(n) n * (n < 5 ? 100 : n < 10 ? 95 : 90) end
Is it a palindrone? - Write function that checks if a given string (case insensitive) is a palindrome.
def is_palindrome str end
def is_palindrome str str.downcase == str.reverse.downcase ? true : false end
def is_palindrome str str.casecmp?(str.reverse) end
Remove duplicates from list - Define a function that removes duplicates from an array of numbers and returns it as a result.
def distinct(seq) end
def distinct(seq) seq.uniq end
String cleaning - Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. For example:
string_clean('! !') == '! !' string_clean('123456789') == '' string_clean('This looks5 grea8t!') == 'This looks great!'
Your harried co-workers are looking to you for a solution to take this garbled text and remove all of the numbers. Your program will take in a string and clean out all numeric characters, and return a string with spacing and special characters ~#$%^&!@*():;"'.,? all intact.
def string_clean(string) end
def string_clean(string) string.gsub(/[0-9]/, '') end
def string_clean(string) string.delete('0-9') end
Who ate the last cookie? - For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is: "Who ate the last cookie? It was (name)!"
Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach! (The reason you return Zach is because the input is a string)
Note: Make sure you return the correct message with correct spaces and punctuation.
def cookie(x) end
def cookie(x) x.kind_of?(String) ? "Who ate the last cookie? It was Zach!" : x.kind_of?(Integer) || x.kind_of?(Float) ? "Who ate the last cookie? It was Monica!" : "Who ate the last cookie? It was the dog!" end
def cookie(x) 'Who ate the last cookie? It was ' << case x when String 'Zach!' when Float, Integer 'Monica!' else 'the dog!' end end
Get number from string - Write a function which removes from string all non-digit characters and parse the remaining to number. E.g: "hell5o wor6ld" -> 56
def get_number_from_string(s) end
def get_number_from_string(s) s.gsub!(/[a-z\W]/, '') return s.to_i end
def get_number_from_string(s) s.scan(/\d+/).join.to_i end