Created
June 17, 2013 13:37
-
-
Save surrealdetective/5796920 to your computer and use it in GitHub Desktop.
ruby review
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Testing / Assertion | |
# Define a method that takes two values and compares them, printing pass or fail | |
def assert_equal(actual, expected) | |
if actual == expected | |
return true | |
else | |
return false | |
end | |
end | |
puts assert_equal(1,1) #=> pass | |
puts assert_equal(2,1) #=> fail | |
# Use assert to test the following: | |
# define a method that creates an Array of Greetings for every person's name | |
# greetings(["Bob", "Tim", "Jake"]) #=> ["Hello Bob!", "Hello Tim!", "Hello Jake!"] | |
def greetings(names) | |
names.each_with_index do |name, index| | |
names[index] = "Hello #{name}!" | |
end | |
end | |
names = ["Brad", "Tim", "Jake"] | |
puts assert_equal( | |
greetings(names), | |
["Hello Brad!", "Hello Tim!", "Hello Jake!"] | |
) | |
# define a method to sum the values of an array. Make this method defend against nils and | |
# other errors | |
def sum(numbers) | |
sum = 0 | |
numbers.each do |number| | |
sum += number.to_i | |
end | |
sum | |
end | |
puts assert_equal sum([]), 0 | |
puts assert_equal sum([1,2]), 3 | |
puts assert_equal sum([1,nil,2]), 3 | |
puts assert_equal sum([1, "2", 2]), 3 | |
# define a method that returns comfortable for temps between 60-80, cold for below and hot | |
# for above. | |
def temperature_bot(temp) | |
if temp.between?(60, 80) | |
return "comfortable" | |
elsif temp > 80 | |
return "hot" | |
elsif temp < 60 | |
return "cold" | |
end | |
end | |
puts assert_equal temperature_bot(65), "comfortable" | |
puts assert_equal temperature_bot(70), "comfortable" | |
puts assert_equal temperature_bot(85), "hot" | |
puts assert_equal temperature_bot(30), "cold" | |
# # define an object, Person, that has a birthdate and a name. Define a method for a person | |
# # that returns their age. | |
class Person | |
YEAR = Time.now.year | |
attr_accessor :name, :birthday | |
def age | |
YEAR - @birthday[-4..-1].to_i | |
end | |
end | |
begin | |
person = Person.new | |
person.name = "Tim Berners-Lee" | |
person.birthday = "06/08/1955" | |
puts assert_equal person.name, "Tim Berners-Lee" | |
puts assert_equal person.birthday, "06/08/1955" | |
puts assert_equal person.age, 58 | |
rescue => e | |
puts "Fail: #{e}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment