开发者

Initialize a multiple levels hash in rails

开发者 https://www.devze.com 2023-02-17 20:58 出处:网络
So I have some codes look like the followin开发者_如何学Gog: @foo ||= {} @foo[:bar] ||= {} @foo[:bar][:baz] ||= {}

So I have some codes look like the followin开发者_如何学Gog:

@foo ||= {}
@foo[:bar] ||= {}
@foo[:bar][:baz] ||= {}

I am not concerning the performance, but the cleanness. Is there a more beautiful way or better way to do so?


{:bar => {:baz => {}}}.merge(@foo)


I think what you have is a good, terse way of writing the code, but below is another way I thought of to do the same thing. It'll still do the job, if you'd prefer to be more verbose:

if @foo.nil?
    @foo = { :bar => { :baz => {} } }
else if @foo[:bar].nil?
    @foo[:bar] = { :baz => {} }
else if @foo[:bar][:baz].nil?
    @foo[:bar][:baz] = {}
end

or

if !@foo
    @foo = { :bar => { :baz => {} } }
else if !@foo[:bar]
    @foo[:bar] = { :baz => {} }
else if !@foo[:bar][:baz]
    @foo[:bar][:baz] = {}
end
0

精彩评论

暂无评论...
验证码 换一张
取 消