中间有一个内联块的Ruby Hash声明 [英] Ruby Hash declaration with an inline block in the middle

查看:85
本文介绍了中间有一个内联块的Ruby Hash声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个XML文档:

<Request>
    <Field1>value1</Field1>
    <Field2>value2</Field2>
    <Section1>
        <Field attribute1="attrval1">value11</Field>
        <Field attribute1="attrval2">value12</Field>
        <Field attribute1="attrval3">value13</Field>
        <Field attribute1="attrval4">value14</Field>
    </Section1>
    <Section2>
        <Fld1>value21</Fld1>
        <Fld2>value22</Fld2>
        <Fld3>value23</Fld3>
    </Section2>
</Request>

通过以下Ruby代码进行解析:

which is parsed by following Ruby code:

xml = Nokogiri::XML(request.raw_post)
req = xml.xpath('/Request')
hash = {
    field1: req.xpath('Field1').text,
    field2: req.xpath('Field2').text,
    section1: req.xpath('Section1/Field').map {|fld|
        {
            attribute1: fld.attr('attribute1'),
            value: fld.text
        }
    },
    section2: req.xpath('Section2').some_method { |sec2|
        {
            fld1: sec2.xpath('Fld1').text,
            fld2: sec2.xpath('Fld2').text,
            fld3: sec2.xpath('Fld3').text
        }
    }
}

Section1的解析是真正的代码段.

Parsing of Section1 is a real working piece of code.

第2节中非重复值的解析是一个概念-我希望不必声明这一点

Parsing of non-repeated values in Section2 is a concept - something I would like to see to not have to declare

sec2 = req.xpath('Section2')

在散列声明之前.

我想看一些内联块.

有什么建议吗?

推荐答案

您也可以在此处使用map:

req.xpath('Section2/*').map { |f| [f.name.downcase.to_sym, f.text] }.to_h
# => {:fld1=>"value21", :fld2=>"value22", :fld3=>"value23"}

这篇关于中间有一个内联块的Ruby Hash声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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