On Thanksgiving I wrote a silly little script that mimicked the popular “What does the fox say?” video. It asked the user for input and returned the animal sound if the name was in the database (a hash).
I wrote an if else statement for the output because that’s what I had been taught at the time. Then I learned about ternary operators and had a devil of a time trying to figure out how to rewrite the if else statement.
- puts "That animal is not in my database!"
- puts ''
- puts animals[response]
animals.include?(response) ? (puts arr_animals[response]) :
(puts "That animal is not in my database!")
For the first few tries I was trying to write the ternary operator using
.nil?. I finally figured out that instead of asking if the hash didn’t include (.nil?) I should ask if it INCLUDES (.include?)