Reputation: 16735
I don't work in Ruby day-to-day, but I'm attempting to brush up on it. On exercism.io, there's an exercise I'm attempting to complete and the solution I came up with isn't working. Here's the test code:
class ResistorColorDuoTest < Minitest::Test
def test_brown_and_black
# skip
assert_equal 10, ResistorColorDuo.value(["brown", "black"])
end
end
This is the solution I came up with:
module ResistorColorDuo
def self.value(colors)
case colors
when (colors - ["brown", "black"]).empty?
10
else
-1
end
end
end
The output from the method is -1. I can't figure out what I've fouled up. Any suggestions are greatly appreciated. Thank you for reading.
Upvotes: 1
Views: 60
Reputation: 3371
Based on: https://stackoverflow.com/a/42269911/14454939
colors = ["brown", "black"]
case
when (colors - ["brown", "black"]).empty?
10
else
-1
end
# => 10
colors = ["brown", "blue"]
case
when (colors - ["brown", "black"]).empty?
10
else
-1
end
# => -1
Edit: I didn't really think of it until now, but is there a reason you can't do?:
colors = ["brown", "blue"]
case colors
when ["brown", "black"]
10
when ["brown", "blue"]
20
else
-1
end
# => 20
or if order shouldn't matter:
colors = ["brown", "blue"]
case colors.sort
when ["black", "brown"] #.sort if you don't want to sort manually
10
when ["blue", "brown"]
20
else
-1
end
# => 20
Upvotes: 2
Reputation: 30071
You're using case
like it was an if
.
(colors - ["brown", "black"]).empty?
evalutes to true
so true
is compared to your colors
switch to if-else
def self.value(colors)
if (colors - ["brown", "black"]).empty?
10
else
-1
end
end
Upvotes: 4