Finally! Ternary Operators

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.

Before:
if animals[response].nil?
- puts "That animal is not in my database!"
-else
- puts ''
- puts animals[response]
-end

After:
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?)

PROBLEM SOLVED!

Leave a Reply