Is there a way to conditionally define a local variable? I’m trying to generate some code where I want to define a local variable but only if the corresponding key to a hash exists. I tried the obvious way of doing it but apparently it does not work:
_locals = {
organization: 'org',
account: 'account'
}
# (account, organization, include_orgs) = _locals.values_at(:account, :organization, :include_orgs) #declares all local variables regardless of key value
if _locals.key? :account
account = _locals[:account]
end
puts defined? include_orgs # returns nil
if _locals.key? :organization
organization = _locals[:organization]
end
puts defined? include_orgs # returns nil
if _locals.key? :include_orgs
include_orgs = _locals[:include_orgs]
end
puts defined? include_orgs # does NOT return nil
if defined? include_orgs
puts include_orgs.inspect
end
# looks like local variables are created INSIDE the if block even if it does not go into the if
I’m working on something that rewrites jbuilders to (plain) ruby, and there’s a lot of existing code that uses defined? in their behavior. I’d like to know if there’s a clean way to conditionally define local variables so I don’t have to rewrite all calls to defined? in the code.