'puts' and 'print'


#1



'puts' and 'print'


In the excercise it ask me to put any text after writing the codes 'puts' or 'print', but is it normal to see "nil" printed right after the text, even if i didn't typed it? 

For example i type < puts "Hello" > and i got printed like this < Hellonil >


#2

That's a good question. This behaviour is normal for puts in Ruby.

The effect of using the puts method is to output text to a screen, but the return value of puts is always nil.

So when you're using puts in this way, you see both the effect of 'puts' as well as the value it returns.

This can be quite confusing initially, but it will make more sense as you learn more about Ruby.


#3

But it happens also when i use "print" so it is fine then?


#4

Yeah. It's normal for print in Ruby too.


#5

In the excercise it ask me to put any text after writing the codes 'puts'
or 'print', but is it normal to see "nil" printed right after the text,
even if i didn't typed it?

Yes. Look up the definition of puts:

http://ruby-doc.org/core-1.9.3/IO.html#method-i-puts

It says that it returns nil. Every expression in Ruby returns a value.
If you type just

1+1

you would expect "2" to be printed - the value of this expression. So if
you type puts(...), you also get the value of this expression printed.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.