Take a look at the Dog
class:
class Dog
attr_accessor :age, :name, :weight
def initialize(params)
@name = params[:name]
@age = params[:age]
@weight = params[:weight]
end
# Takes a list of up to three dogs and determine whether they'll play nice.
# Dogs of highly varied weights can't play nice together, and groups with
# too many puppies and large dogs don't play nice either.
def self.play_nice(dog_one=nil, dog_two=nil, dog_three=nil)
dogs = [dog_one, dog_two, dog_three]
weights = dogs.map(&:weight)
heaviest = dogs[weights.index(weights.max)]
lightest = dogs[weights.index(weights.min)]
big_dogs = heaviest.weight > 60
too_many_puppies = dogs.count do |dog|
dog.age < 5
end >= 2
if heaviest.weight - lightest.weight > 20
"#{heaviest.name} is too large to play nice with little #{lightest.name}."
elsif too_many_puppies && big_dogs
"These pups are too rambunctious to place nice together."
else
"Sure, they'll play nice!"
end
end
end
A. Dog::play_nice
. Doesn't quite do what the comment describes. There's a bug. Can you spot it? (Don't worry, you can still answer parts B, C, and D even if you can't find the bug.)
- Give example values for the arguments that expose the bug (i.e. hit an unexpected error).
- Edit the method to fix the bug. Explain how the fix works.
B. Add comments to each line of code explaining what it does in your own words.
C. What would be the effect of switching the if
and elsif
clauses, so that the last lines of the method read like this instead?
if too_many_puppies && big_dogs
"These pups are too rambunctious to place nice together."
elsif heaviest.weight - lightest.weight > 20
"#{heaviest.name} is too large to play nice with little #{lightest.name}."
else
"Sure, they'll play nice!"
end
D. Write a new method that generalizes this one to work for an arbitrarily large list of dogs.
Use React (tutorial) to build a simple web application with the following properties:
- It starts with two text inputs accepting numbers
- A sum of the two numbers is displayed based on the live value of the fields
- You can click a button to add additional number fields, and the sum includes all numbers
You may use present your solution however you like, e.g. a zipped directory of your code, or a link to a JSFiddle.