fguillen
fguillen

Reputation: 38888

Ruby: Using a not defined variable

How can I make something like this?

1.9.3p286 :006 > defined? activated_flag
 => nil 
1.9.3p286 :007 > puts (activated_flat ? "activated!" : "no activated")

I would like to see here no activated, but instead I have:

NameError: undefined local variable or method `activated_flat' for main:Object
  from (irb):7
  from /Users/fguillen/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'

Upvotes: 0

Views: 279

Answers (2)

fguillen
fguillen

Reputation: 38888

The simplest way I have found is adding a fallback initialization like:

activated_flag ||= false

But as I'm using this variable in erb partials this fallback initialization looks ugly.

Upvotes: 0

user904990
user904990

Reputation:

why not using defined?:

puts (defined?(activated_flat) ? "activated!" : "no activated")
#=> no activated

Upvotes: 2

Related Questions