简体   繁体   中英

Variable assignment if it doesn't exist

I want to assign an object to a variable containing another variable unless that variable doesn't exist, in which case I want to assign an empty object.

I have this code which works:

if @myvar['one']['two']
  newvar = {:three => @config['one']['two']}
else
  input = {}
end

Is there a neater way to do this?

If I understand your question correctly, you could do something like:

newvar = if @myvar['one']['two']
           {:three => @config['one']['two']}
         else
           {}
         end

You could then use newvar as the variable assigned either to a populated hash or an empty hash. Additionally, you'll want to check to ensure @myvar exists, and has a key of 'one' before calling 'two' :

newvar = if @myvar && @myvar.has_key?('one') && @myvar['one']['two']
           {:three => @config['one']['two']}
         else
           {}
         end

Assuming your code works... In one line:

@myvar['one']['two'] ? newvar = {:three => @config['one']['two']} : input = {}

If you want to prevent a nil @myvar and ensure it has a key of one and two :

@myvar && @myvar.has_key?('one') && @myvar['one']['two'] ? newvar = {:three => @config['one']['two']} : input = {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM