instance variable not initialized warning

Discussion in 'Ruby' started by Esad Hajdarevic, Oct 19, 2006.

  1. Hi!

    In the following piece of code:

    class Foo
    def bar
    if @var.nil?
    puts "First assignment"
    @var = 1;
    @var +=1;

    When I run ruby (1.8.4)with -d ($DEBUG=true) I get to see the following

    test.rb:3: warning: instance variable @var not initialized

    Does it make sense to spit out this warning even if you are doing
    something safe such as calling Object#nil?

    What do you think?
    Esad Hajdarevic, Oct 19, 2006
    1. Advertisements

  2. The interpreter does not flag methods as 'safe' or 'unsafe'.

    If you want to get rid of the warning, you can use

    if defined? @var


    @var ||= 0
    @var += 1

    Yoann Guillot, Oct 19, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.