Arup Rakshit
Arup Rakshit

Reputation: 118299

How "puts" statement works in Ruby?

I knew that puts return always nil by itself.

But knowing that fact already I have started to play around it. here it is:

>> puts

=> nil # Good, you are doing what I expected.

>> puts 15
15
=> nil # nil is for puts and 15 it printed,as it is assigned to do. perfect still.

>> puts a = 5 + 2
7
=> nil # still good.

Now I will do a bit more with puts to see how robust it is.

>> puts a= 5 + 2;b= 2+3
7
=> 5 #ahh! where is nil?

>> puts a= 5 + 2;b= 2+3;c= 4+8
7
=> 12 # again no nil. Another confusion created here that why 12 and 7 only, how 5 has been skipped?

How puts nil value has been suppressed ?

Okay, so lets test another way where nil has been gone.

>> x=puts a= 5 + 2;b= 2+3;c= 4+8
7
=> 12

>> puts x

=> nil # humm, nil is there. but why not nil => nil? Confusion here again goes up. whose nil is it?

Can anyone help me by saying the actual behaviour of puts in Ruby's world?

Upvotes: 0

Views: 4893

Answers (4)

Colonel Panic
Colonel Panic

Reputation: 137512

Your problem isn't with puts, but what the prompt does with commands containing multiple statements (separated by semi-colons).

Think on this example:

irb(main):001:0> "first";"second"
=> "second"

Upvotes: 1

steenslag
steenslag

Reputation: 80105

putscalls to_s on it's argument, that's why puts 1 works. puts nil is the same as puts nil.to_s, and that is the same as puts "" (note the blank line in the IRB output).

The rest is just irb outputting the result of the last executed line, before waiting on new input.

Upvotes: 1

Frederick Cheung
Frederick Cheung

Reputation: 84182

This doesn't have much to do with puts.

A semicolon separates multiple expressions. irb will in this case only display what the last expression evaluated to.

Upvotes: 2

Kyle
Kyle

Reputation: 22278

The repl, irb I will assume, is evaluating the statement(s) you enter and displaying the value of the last statement evaluated.

Consider this:

>> p = puts "hello"; 5
hello
 => 5 
>> p
 => nil 

puts is still returning nil but the repl is displaying the result of the last statement, 5

Upvotes: 2

Related Questions