Only 1 line showing


#1

Hello,
I'm on lesson 13 - Variables and Data types

This is my code:

my_name="Audrey"
my_age=27

But the screen only shows me: 27
Why didn't it write my name as well?
Thanks for your help!!


#2

Hey @audrey88

The reason the screen only displays 27, is because "my_age=27" is the last statement the program runs, and the behavior of Ruby works such that the last statement is always returned (in this case, to the compiler, which is then shown).

If you tried switching the order of your variables, it would state "Audrey" instead of 27

If you want to output both variables, you could write "puts my_name" and "puts my_age" after assigning the variables, like so:

my_name="Audrey"
puts my_name
my_age=27
puts my_age

Take note though, if the last statement is a puts command, you will see nil at the end of output screen. This is because the puts method returns nil, and with it being the last statement, the nil value is passed to the compiler and shown.


#3

Thanks a lot! I understand now :slight_smile:

So I guess it's better to use print instead of puts to not have the nil at the end?


#4

Hey

Print will also return nil, with the downside of not separating different outputs on new lines.
It's completely fine that the output says nil at the end (or anything else depending on what happens last in the program), I just wanted to notify about it being displayed since I've seen questions about it previously


#5

Thanks for the precision!