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!
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
Ingrid Bardales10,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
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
Rachelle Wood15,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.
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
if name.empty? name else name = "Andrew"