嵌套散列定义?() [英] Nested hash defined?()
问题描述
确定 @hash [:key1] [:key2]
是否被定义,如果不会抛出错误,最简洁的方法是什么? @hash
或 @hash [:key1]
为零?
defined(?hash [:key1] [:key2])
不确定是否定义了:key2
)
Rails)或Backports,你可以使用 try
:
@hash [ :key1] .try(:fetch,:key2)
你甚至可以处理 @hash
存在
@ hash.try(:fetch,:key1).try(:fetch,:key2)
您希望 @hash
始终为缺少的键返回散列值:
@hash = Hash.new {| h,k | h [k] = {}}
@hash [:foo]#=> {}
您也可以定义这个递归:
def recursive_hash
Hash.new {| h,k | h [k] = recursive_hash}
end
@hash = recursive_hash
@hash [:foo] [:bar] [:blah] = 10
@hash #=> {:foo => {:bar => {:blah => 10}}}
但是要回答您的问题:
模块HasNestedKey
Hash.send(:include,self)
def has_nested_key?(* args)
返回false,除非sub = self [ args.shift]
如果args.empty返回true?
sub.respond_to?(:has_nested_key?)和sub.has_nested_key?(* args)
end
end
@ hash.has_nested_key? :key1,:key2
What's the most concise way to determine if @hash[:key1][:key2]
is defined, that does not throw an error if @hash
or @hash[:key1]
are nil?
defined?(@hash[:key1][:key2])
returns True if @hash[:key1]
exists (it does not determine whether :key2
is defined)
When using ActiveSupport (Rails) or Backports, you can use try
:
@hash[:key1].try(:fetch, :key2)
You could even handle @hash
being nil
:
@hash.try(:fetch, :key1).try(:fetch, :key2)
If you want @hash
to always return a hash for a missing key:
@hash = Hash.new { |h,k| h[k] = {} }
@hash[:foo] # => {}
You could also define this recursive:
def recursive_hash
Hash.new { |h,k| h[k] = recursive_hash }
end
@hash = recursive_hash
@hash[:foo][:bar][:blah] = 10
@hash # => {:foo => {:bar => {:blah => 10}}}
But to answer your question:
module HasNestedKey
Hash.send(:include, self)
def has_nested_key?(*args)
return false unless sub = self[args.shift]
return true if args.empty?
sub.respond_to?(:has_nested_key?) and sub.has_nested_key?(*args)
end
end
@hash.has_nested_key? :key1, :key2
这篇关于嵌套散列定义?()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!