If variable is not empty

(MOVED FROM RUBY FORUM)

How can I create an if statement to check if a variable contains a
value? If it does contain a value, I want to send an email. I'm doing
the following but it doesn't work...

You can try this

     Notifier.appointment_booked(@appointment).deliver unless
@appointment.client.email.nil?

Luis Saffie wrote in post #949585:

You can try this

     Notifier.appointment_booked(@appointment).deliver unless
@appointment.client.email.nil?

According to the logs, it's still trying to send an email. Note "Sent
mail to" but of course, it's empty because there is no email for that
client.

right, I was checking for nil but that's a string "". Instead do this.

Notifier.appointment_booked(@appointment).deliver unless
@appointment.client.email.empty?

Luis Saffie wrote in post #949592:

right, I was checking for nil but that's a string "". Instead do this.

Notifier.appointment_booked(@appointment).deliver unless
@appointment.client.email.empty?

AWESOME!!! Finally it works!

Thank you so much :smiley:

Better off using the Rails method .blank? which returns true for nil,
empty strings, empty arrays, all sorts:

@appointment.client.email.blank?

http://api.rubyonrails.org/classes/Object.html#method-i-blank

Michael Pavling wrote in post #949603:

Hi, you can do the following:

unless appointment.client.email.blank?
   # do something
end

Next, you may want to do additional because some objects in the chain could be nil.

Good luck,

-Conrad

Hi, you can do the following:

unless appointment.client.email.blank?
  # do something
end

Next, you may want to do additional because some objects in the chain could be nil.

try() comes in handy for this...

unless appointment.client.try(:email).blank?

-philip