从任意深度的散列中优雅地提取所有字符串 [英] Elegantly extracting all strings from an arbitrarily deep hash

查看:81
本文介绍了从任意深度的散列中优雅地提取所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是确定这样的散列中是否有空白:

My goal is to determine whether there is a blank in a hash like this:

{"departure_time_slots"=>{"date"=>[""], "time"=>{"start"=>[""], "end"=>[""]}}}

字符串嵌套任意时间。我不想手动检查它们中的每一个。如果我能够提取所有的字符串,无论它们的深度如何,都会很好。有没有简单的方法来做到这一点?

The strings are nested arbitrary times. I do not want to check each of them manually. It would be nice if I can extract all the strings regardless of their depth. Is there a simple way to do that?

推荐答案

下面是如何提取值的示例。但是,您仍然会遇到将值与键匹配的问题。你不可能同时拥有两个。

Here's an example of how you can extract the values. However you will still have the problem of matching the values to the keys. You can't really have both at the same time.

# Extend the Hash class
class Hash
  def recursive_values
    self.values.collect { |v|
      v.is_a?(Hash) ? v.recursive_values : v
    }.flatten
  end
end

用法:

Usage:

h = {"departure_time_slots"=>{"date"=>[""], "time"=>{"start"=>[""], "end"=>[""]}}}
h.recursive_values
=> ["", "", ""]

这篇关于从任意深度的散列中优雅地提取所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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