MCVE (Minimal, Complete, Verifiable Example) in order to reproduce the same problem as mine:
at rspec file place:
RSpec.describe 'Predicate Enumerable Exercises' do
describe 'coffee drink exercise' do
it 'returns true when espresso is included' do
drink_list = ["milk", "juice", "espresso"]
expect(coffee_drink?(drink_list)).to be true
end
end
describe 'valid scores exercise' do
it 'returns true when only one score is a 10' do
score_list = { easy_to_read: 10, uses_best_practices: 8, clever: 7 }
perfect_score = 10
expect(valid_scores?(score_list, perfect_score)).to be true
end
end
end
at the actual functions file:
def coffee_drink?(drink_list)
drink_list.include?("coffee" || "espresso")
end
def valid_scores?(score_list, perfect_score)
score_list.one?{|score| score == perfect_score}
end
I am having a hard time figuring out what is wrong in my code because I am relying on built-in methods (one?, include?) so I'm not sure what is the actual problem
I created 2 methods, coffee_drink?(drink_list) and valid_scores?(score_list, perfect_score).
coffee_drink? gets an array, which then returns true only if it includes either the word coffee or espresso.
I used the following to return the expected: drink_list.include?("coffee" || "espresso")
But when I have espresso on my list and no coffee the console returns:
returns true when espresso is included (FAILED - 1)
Where drink_list is ["milk", "juice", "espresso"]
For valid_scores? it gets an array and integer, and returns true when only one value in the array is equal to that integer. But I expected that score_list.one?{|score| score == perfect_score} would return true when only one value is true. Instead I get:
returns true when only one score is a 10 (FAILED - 2)
Where the array is
score_list = { easy_to_read: 10, uses_best_practices: 8, clever: 7 }
and the integer is
perfect_score = 10
I am using ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux] if that helps.
Your include? code behaves different than expected because:
"coffee" || "espresso" #=> "coffee"
# so
drink_list.include?("coffee" || "espresso")
# evaluates to
drink_list.include?("coffee")
You'll have to either use 2 separate include? calls, or some other option like any? or &.
drink_list.include?("coffee") || drink_list.include?("espresso")
# or
drink_list.any? { |drink| drink == "coffee" || drink == "espresso" }
drink_list.any?(/\A(coffee|espresso)\z/)
(drink_list & ["coffee", "espresso"]).size.positive? # !(...).empty? also works
Your one? code behaves different than expected because score_list is not an array, but a hash (dictionary/map in other languages). A hash consists of key/value pairs which are passed as array ([key, value]) to the one? block.
score_list.one? { |pair| pair.last == perfect_score }
Alternatively you can use array decomposition:
score_list.one? { |key, value| value == perfect_score }
Or retrieve only the values beforehand:
score_list.values.one? { |score| score == perfect_score }