Truthy and falsey

In the last exercise you found out something interesting:

true && "ham" #=> "ham"

Which is a bit weird. There are actually two things going on here:

  1. The string ham is considered to be true
  2. The overall statement evaluates to the last expression in it

Truthy and falsey

In ruby there are only two values that are considered false: false and nil. We say that false and nil are falsey.

Everything else is considered to be true. We say that all other objects are truthy.

What we mean by ‘considered to be true’ is that if that value is used as a conditional in an if statement then the if code runs:

if 5
x = 1
else
x = 2
end

x #=> 1

In the above block of code, as 5 is truthy, the variable x is set to 1.

Exercise

The bar is trialling a new initiative: Tuesday evenings is going to be “Seniors Night”, with only those aged 65+ allowed.

  1. Add a dropdown box for day of the week to the form
  2. Add logic to app.rb so that:
    • If you’re under 18, you see the no drink message
    • If you’re 18 or over, and it isn’t Tuesday, you see the welcome message
    • On Tuesdays, if you’re 65 or over, you get a welcome message, along with a reminder that it’s seniors night.
    • On Tuesdays, if you’re under 65, you get a message explaining you can’t drink because it’s seniors night.


Prev | Next