Created
October 25, 2015 01:30
-
-
Save martinlaws/1b88ebc5c5e0547ecd25 to your computer and use it in GitHub Desktop.
rspec exercises - lhl wk1e
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
### SETUP | |
require 'rspec' | |
### LOGIC (fix me) | |
def hello(who) | |
"hello #{who}!" | |
end | |
### TEST CODE (don't touch me) | |
describe '#hello' do | |
it 'returns "hello world!" when "world" is passed in' do | |
result = hello('world') | |
expect(result).to eq('hello world!') | |
end | |
end |
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
### SETUP | |
require 'rspec' | |
### LOGIC (fix me) | |
# Returns the average of all the numbers in the array | |
def average(numbers) | |
if numbers.class == Array | |
if !numbers.empty? | |
sum = 0 | |
numbers.each do |n| | |
n = n.to_f | |
sum += n | |
end | |
sum / numbers.size | |
else | |
return nil | |
end | |
else | |
return nil | |
end | |
end | |
### TEST CODE (don't touch me) | |
describe '#average' do | |
it 'returns nil for empty array' do | |
result = average([]) | |
expect(result).to be_nil | |
end | |
it 'returns nil when nil is passed in' do | |
result = average(nil) | |
expect(result).to be_nil | |
end | |
it 'returns 4 for 3,4,5' do | |
result = average([3, 4, 5]) | |
expect(result).to eq(4) | |
end | |
it 'can handle numbers represented as strings' do | |
result = average([10, '20', 30]) | |
expect(result).to eq(20) | |
end | |
it 'can handle floats' do | |
result = average([1.0, 1.5, 2.0]) | |
expect(result).to eq(1.5) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment