Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJohn Fisher
7,974 Pointsinclude? method help
Hi.
I'm just trying to figure a few things out in Ruby.
I want to use an if else statement to check if the input from a user uses certain combinations of words/strings.
answer = gets.chomp
if answer.include? "word1" && "word2"
puts "response 1"
elsif answer.include? "word1" && "word3"
puts "response 2"
elsif answer.include? "word3" && "word4"
puts "response 3"
else
puts "try again"
end
however, I'm getting some unexpected results.
if the user inputs just "word1" they get "try again". That's seems fine
if user inputs a string with "word1" and "word2" they get "response 1". Also seems fine
if user inputs a string with "word1" and "word3" they get "response 2". This is fine too.
However, if the user enters "word3" and "word4" they also get "response 2"
I'm not sure what I'm doing wrong. I can't find much information on the include? method. Does it except conditionals like &&?
Any suggestions appreciated. Thanks
2 Answers
Justin Horner
Treehouse Guest TeacherHello John,
Do you want to use OR instead of AND so that if a user types "word1" OR "word2" they get "response 1"? You'll want to include parenthesis for the include? method. In this case your code would look like:
answer = gets.chomp
if answer.include?("word1") || answer.include?("word2")
puts "response 1"
elsif answer.include?("word1") || answer.include?("word3")
puts "response 2"
elsif answer.include?("word3") || answer.include?("word4")
puts "response 3"
else
puts "try again"
end
I hope this helps.
John Fisher
7,974 PointsAfter much trial and error, I figured it out.
needs to look like this...
if answer.include?("word1") && answer.include?("word2")
I tried this originally without the parenthesis and it crashed.
John Fisher
7,974 PointsJohn Fisher
7,974 PointsThanks Justin
Yeah, I was getting the syntax wrong. Was forgetting to put the answer.include? on the righthand side of the &&
All good practice tho :)
Justin Horner
Treehouse Guest TeacherJustin Horner
Treehouse Guest TeacherYou're welcome!