Confusion with Ruby printing mechanics

Here I just played to see how printing statement behaves with “nil”
values. Here we go:

p nil
nil
=> nil #good as expected.

puts nil
#as nil.to_s causes the “blank” in the first line.
=> nil #good as expected.

p puts nil
#as nil.to_s causes the “blank” in the first line
nil
=> nil # good as expected, as p works here on the return value of puts.

=========================

Confusion begins with the below :

p(puts(print(“hi”)))
hi
nil
=> nil # this is the actual output.

But from the above analysis I expected the below:

p(puts(print(“hi”)))
hi

nil
=> nil

Could you explain the gap between my assumption and the actual one?

Thanks.

Print doesn’t append a newline, so the puts’d nil is tacked onto the end
of
the ‘hi’

I’d write more, but I hate typing on my phone.

Sent from my phone, so excuse the typos.

Matthew K. wrote in post #1097228:

Print doesn’t append a newline, so the puts’d nil is tacked onto the end
of
the ‘hi’

I’d write more, but I hate typing on my phone.

Sent from my phone, so excuse the typos.

Humm! perfect catch tried and tested. and you got 100 out of 100. :slight_smile: :slight_smile:

p(puts(print(“hi\n”)))
hi

nil
=> nil

Confusion begins with the below :

p(puts(print(“hi”)))
hi
nil
=> nil # this is the actual output.

But from the above analysis I expected the below:

p(puts(print(“hi”)))
hi

nil
=> nil

Well there you are adding only one newline, it’s added with puts. You
can find what you want also in this way:

p print(“hi\n\n”)

Damián M. González wrote in post #1097245:

Confusion begins with the below :

Well there you are adding only one newline, it’s added with puts. You
can find what you want also in this way:

p print(“hi\n\n”)

I actually had confusion with the below:

p(puts(print(“hi”)))
hi
nil
=> nil # this is the actual output.

how it comes? to catch this i added one ‘\n’.

why do you have confusion?? didnt they already told you how the print
commands work?

in your sample:
print(“hi”) does “hi” and returns nil
puts(nil) does “\n” and returns nil
p(nil) does “nil\n” and returns nil (the object it gets)

was it that hard to get??

Hans M. wrote in post #1097261:

why do you have confusion?? didnt they already told you how the print
commands work?

in your sample:
print(“hi”) does “hi” and returns nil
puts(nil) does “\n” and returns nil
p(nil) does “nil\n” and returns nil (the object it gets)

was it that hard to get??

Nopes! friend… I am set at all. I just told him,what made me confused.

Thanks

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs