Why does irb print nil sometimes

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”

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
1 Like

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

1 Like