Forum: Ruby Trouble defining variable correctly

D0bb24ff5849606b3b03c1fb9c6c0179?d=identicon&s=25 Matthew Stevenson (stevensonmt)
on 2014-06-23 00:57
The code below is not working the way I'd like and I can't figure out
why.
It returns the error "undefined local variable or method `triggers'".
But I have defined triggers as an array.  What am I not getting?

def trigger_list
    triggers = Array.new
    def get_triggers
      puts "Please enter program that you want to trigger the power
management switch."
      triggers.push gets.chomp
      puts triggers
    end
    get_triggers
    def more_triggers
      puts "Do you have other programs you want to trigger the power
management switch? [y/n]"
      answer = gets.chomp.downcase
      if answer == "y"
        get_triggers
      else
        puts "Okay, triggering progams list is complete."
      end
    end
    more_triggers
  end
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2014-06-23 23:06
The word 'def' creates a new scope, which means that inside the def, you
can't refer to local variables created outside the def.   Global
variables and constants created outside the def can be summoned inside
the def.

Also, unless you enjoy typing `Array.new`, you can just type `[]`, e.g.

    triggers = []
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.