嵌套散列定义?() [英] Nested hash defined?()

查看:111
本文介绍了嵌套散列定义?()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定 @hash [:key1] [:key2] 是否被定义,如果不会抛出错误,最简洁的方法是什么? @hash @hash [:key1] 为零?

defined(?hash [:key1] [:key2])不确定是否定义了:key2

解决方案

Rails)或Backports,你可以使用 try

  @hash [ :key1] .try(:fetch,:key2)

你甚至可以处理 @hash 存在 nil :

  @ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆