I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. I would like to refactoring the following code to one line:
args ||= {}
@i_vars = {}
args.each { |key, opts| @i_vars[key] = IVar.new(key, opts, args.keys) }
I thought to use the inject method something like this:
args ||= {}
@ivars = args.inject({}) { |result, (key, opts)| result.merge( @i_vars[key] = IVar.new(key, opts, args.keys) ) }
However, the latter code returns different results when setting the @i_vars variable. I tried also others implementations of the inject method but without success.
There is a way to refactoring the code? or, maybe, should I use some other method or some RoR feature (unknown to me)?
What you should write in the
injectblock:But no need to use
injectoreach_with_objectto build a hash, we haveHash[pairs]:However, I wouldn’t obsess with one-liners, I’d write an equivalent but more clear code: