Ruby:将嵌套的Ruby哈希转换为未嵌套的哈希 [英] Ruby: Converting a nested Ruby hash to an un-nested one

查看:123
本文介绍了Ruby:将嵌套的Ruby哈希转换为未嵌套的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {
id => - ct,
factualId=>,
outOfBusiness=> false,
publishedAt=>2012-03-09 11 :02:01,
general=> {
name=>A cote,
timeZone=>EST,
desc=>À™CÃ'té是位于奥克兰迷人的
Rockridge区的一家小餐馆,在
主餐厅和阳光明媚的天井中,舒适的餐桌围绕着大型公共餐桌营造节日氛围
体现时尚地中海美食的小盘子由友善而知识渊博的员工为您提供
家庭式的款待。\ \\ nMenu物品配以精心挑选的
a精选超过40种葡萄酒,以及高达
的各种瓶装葡萄酒,特色饮料包括新鲜水果,珍贵的
botaniqu ,
website=>http://acoterestaurant.com/
},
location=> {
address1=>5478 College Ave,
address2=>,
city=>Oakland,
region >CA,
country=>US,
postcode=>94618,
longitude=> 37.84235,
latitude=> -122.25222
},
phones=> {
main=>510-655-6469,
fax =>无
},
小时=> {
mon=> {start=>,end=>}} ,
tue=> {start=>,end=>},
wed=> {start=> ,end=>},
thu=> {start=>,end=>},
fri=> ; {start=>,end=>},
sat=> {start=>,end=>}} ,
sun=> {start=>,end=>},
holidaySchedule=>
},
businessType=>Restaurant
}

它有几个嵌套的属性,如:

 wed=> {start=> ,end=>} 

我需要将此对象转换为unnested hash在Ruby中。理想情况下,我想检测一个属性是否嵌套,并作出相应的反应,I.E.当它确定属性' wed '被嵌套时,它将取出其数据并存储在字段' wed-start '和' wed-end ',或类似的东西。



任何人都有关于如何入门的提示?

解决方案

这是第一次完整解决方案。我相信你可以写得更优雅,但这似乎很清楚。如果你把它保存在一个Ruby文件中并运行它,你将得到我在下面显示的输出。

  class Hash 
def unnest
new_hash = {}
each | key,val |
if val.is_a?(Hash)
new_hash.merge!(val.prefix_keys(#{key} - ))
else
new_hash [key] = val
end
end
new_hash
end

def prefix_keys(前缀)
哈希[map {| key,val | [前缀+键,val]}] unnest
end
end

p({a=> 2,f=> 5})。
p({a=> {b=> 3},f=> 5})unnest
p({a=> {b > {c=> 4},f=> 5}})unnest



输出:

  {a=> 2,f=> 5} 
{ab=> 3,f=> 5}
{abc=> 4,af=> 5}
/ pre>

Right now, I have a server call kicking back the following Ruby hash:

{
  "id"=>"-ct",
  "factualId"=>"",
  "outOfBusiness"=>false,
  "publishedAt"=>"2012-03-09 11:02:01",
  "general"=>{
    "name"=>"A Cote",
    "timeZone"=>"EST",
    "desc"=>"À Côté is a small-plates restaurant in Oakland's charming
            Rockridge district. Cozy tables surround large communal tables in both
            the main dining room and on the sunny patio to create a festive atmosphere.
              Small plates reflecting the best of seasonal Mediterranean cuisine are served
            family-style by a friendly and knowledgeable staff.\nMenu items are paired with
            a carefully chosen selection of over 40 wines by the glass as well as a highly
            diverse bottled wine menu. Specialty drinks featuring fresh fruits, rare
            botaniques and fine liqueurs are featured at the bar.",
    "website"=>"http://acoterestaurant.com/"
  },
  "location"=>{
    "address1"=>"5478 College Ave",
    "address2"=>"",
    "city"=>"Oakland",
    "region"=>"CA",
    "country"=>"US",
    "postcode"=>"94618",
    "longitude"=>37.84235,
    "latitude"=>-122.25222
  },
  "phones"=>{
    "main"=>"510-655-6469",
    "fax"=>nil
  },
  "hours"=>{
    "mon"=>{"start"=>"", "end"=>""},
    "tue"=>{"start"=>"", "end"=>""},
    "wed"=>{"start"=>"", "end"=>""},
    "thu"=>{"start"=>"", "end"=>""},
    "fri"=>{"start"=>"", "end"=>""},
    "sat"=>{"start"=>"", "end"=>""},
    "sun"=>{"start"=>"", "end"=>""},
    "holidaySchedule"=>""
  },
  "businessType"=>"Restaurant"
}

It's got several attributes which are nested, such as:

"wed"=>{"start"=>"", "end"=>""}

I need to convert this object into a unnested hash in Ruby. Ideally, I'd like to detect if an attribute is nested, and respond accordingly, I.E. when it determines the attribute 'wed' is nested, it pulls out its data and stores in the fields 'wed-start' and 'wed-end', or something similar.

Anyone have any tips on how to get started?

解决方案

Here's a first cut at a complete solution. I'm sure you can write it more elegantly, but this seems fairly clear. If you save this in a Ruby file and run it, you'll get the output I show below.

class Hash
  def unnest
    new_hash = {}
    each do |key,val|
      if val.is_a?(Hash)
        new_hash.merge!(val.prefix_keys("#{key}-"))
      else
        new_hash[key] = val
      end
    end
    new_hash
  end

  def prefix_keys(prefix)
    Hash[map{|key,val| [prefix + key, val]}].unnest
  end
end

p ({"a" => 2, "f" => 5}).unnest
p ({"a" => {"b" => 3}, "f" => 5}).unnest
p ({"a" => {"b" => {"c" => 4}, "f" => 5}}).unnest

Output:

{"a"=>2, "f"=>5}
{"a-b"=>3, "f"=>5}
{"a-b-c"=>4, "a-f"=>5}

这篇关于Ruby:将嵌套的Ruby哈希转换为未嵌套的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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