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 trial

Ruby Ruby Booleans Ruby Booleans Conditional Assignment

Ingrid Bardales
Ingrid Bardales
10,616 Points

conditional assignment: if variable is an empty string why doesn't this snippet return the else statement

name = "Jason"

if defined?(name) name else name = "Andrew" end

puts name

exit

This snippet in the video lesson returns Jason, so i wanted to know what it would return if I left the variable name as an empty string, like so: name = ""..thinking that it might return Adrew...but it returned nothing.
Can someone please explain why? Thanks a million in advance!! Ingrid

If you post up the code for the defined method I could probably give you an answer.

Ingrid Bardales
Ingrid Bardales
10,616 Points

Hi Andrew, thanks for replying. The code below is all the code for this example. It's the last video under Ruby Boolean. Sorry that i don't have any more information.

name = "Jason"

if defined?(name) name else name = "Andrew" end

puts name

exit

2 Answers

Rachelle Wood
Rachelle Wood
15,362 Points

It is because if you define name = "" you are in fact assigning an empty string to name. Since name is defined to this empty string, you return the empty string. Andrew will only appear on your screen if you don't assign the name variable.

Ingrid Bardales
Ingrid Bardales
10,616 Points

Thank you so very much!!! I just about given up on this.

Rachelle Wood
Rachelle Wood
15,362 Points

You're very welcome! Glad I could help.

Since I can't see your method defined? , you can do something nice and built in from Ruby like so:

name = "Jason"

name.empty? ? name = "Andrew": name --> ternary operator

OR

if name.empty? name else name = "Andrew"

Ingrid Bardales
Ingrid Bardales
10,616 Points

Hi JoJo thanks for replying, the code below is the only code that was used for the example. It's the last video under Ruby Boolean. Sorry i don't have any more information.

Thanks, Ingrid

name = "Jason"

if defined?(name) name else name = "Andrew" end

puts name

exit