← Back to Upcase

Why does irb print nil sometimes


(Shankar Dhanasekaran) #1

I go to IRB and type

puts “Shankar”

// I get the below

Shankar

=> nil

the same goes when I type

a = “Shankar”

puts a

// I get the below

Shankar

=> nil

However, when I type this, I don’t get ‘nil’

a = [‘shankar’, ‘devy’]

// I am typing without ‘puts’

a[0]

=> “shankar”


(George Brocklehurst) #2

IRB will output the return value of the statement typed. When you see a nil after puts it is because the puts method returns nil.

Consider the following method, which calls puts and then returns the symbol :done:

def custom_puts(x)
  puts x
  :done
end

If we used this in IRB, this is what we’d see:

> custom_puts 'George'
George
 => :done

(Shankar Dhanasekaran) #3

thanks @georgebrock for the excellent reply! I now understand this.