1

I'm a beginner studying Ruby and I noticed that when I use this website (https://repl.it/) to code, '=> nil' sometimes appears in the output. However, when I use Sublime Text to code, it does not appear at all.

1) Is it important for it to appear in the output? If so, why?

2) How can I make it so that it does appear in Sublime Text?

Thanks!

Tina Limbu
  • 23
  • 3
  • You don't want it to appear in Sublime Text, that would make all of your Ruby invalid. – user229044 Jun 07 '18 at 19:50
  • `nil` is the return value in the last statement of the script. You can get the same result when running your own `.rb` scripts from the terminal. If you use `ruby file_name.rb` it's only going to output everything you write to stdout and stderr (for example `puts` statements). But if you run it from within *irb* and use `load 'file_name.rb'` you're also going to get the return value of the script as well. See: https://stackoverflow.com/q/6149850/3982562 – 3limin4t0r Jun 07 '18 at 21:26

1 Answers1

2

nil in this case is just the return value of your method call. It didn't return anything. The repl prints it out for you, but when you run a Ruby file, you won't see it.

e.g. in pry, irb, repl.it, etc.

puts 5

prints

5
=> nil

The puts command prints 5, then returns nil. The repl prints that for you, so you know what the return value was. You can try it for yourself

def test
  puts 'test'
  return 5
end
test

prints

test
=> 5

If you want it to appear when running a file, you can print the return of the function. e.g.

puts "=> #{test.inspect}"

result

test
=> 5
=> nil # this line only if running in repl
iCodeSometime
  • 1,444
  • 15
  • 30
  • 2
    string interpolation of `nil` would be "" so this line `puts "=> #{tes}"` would output `=> ` if `test` returned `nil` you could use `inspect` e.g. `puts "=> #{nil.inspect}"` will output `=> nil` – engineersmnky Jun 07 '18 at 20:41