"0.4mA", "power"=>"15-6ren">
gpt4 book ai didi

ruby - 遍历 ruby​​ (jekyll) 中的哈希数组

转载 作者:太空宇宙 更新时间:2023-11-03 18:09:07 24 4
gpt4 key购买 nike

我正在为 Jekyll 写一个插件,这样我就可以比较一些产品数据,我正在返回像这样的哈希数组,以便在我的模板中可用:

data = [{"current"=>"0.4mA", "power"=>"15w"}, {"current"=>"1A", "power"=>"5w"}]

但是现在,当我使用 liquid 遍历它们时:

<table>
{% for h in data %}
<tr>
{% for p in h %}
<td>{{ p[0] }}</td>
<td>{{ p[1] }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>

我无法并排列出属性,因为我正在通过哈希一次一个,所以我最终将它们一个放在另一个下面。

我应该如何从插件做相反的准备数据,这样我就可以能够在我的模板中做我想做的事吗?

编辑:

所以要清楚一点,如何从上面的数组中获取以下结构使用纯 ruby 的哈希值?:

p1['current'] = '0.4mA'
p1['power'] = '15w'
... *may have more of these, depending on number of key:value pairs in the hash
p1['...'] = '...'

p2['current'] = '1A'
p2['power'] = '5w'
... *may have more of these, depending on number of key:value pairs in the hash
p2['...'] = '...'

最佳答案

如果您想要按行显示属性(例如,一行表示“电流”,一行表示“功率”等)并且您不想对显示模板进行任何更改,您可以转换您的数据像这样在 Ruby 中散列 - 以下之一(也许两者)应该适用于您的模板:

如果您知道 data 中的每个散列都将包含所有键,您可以从第一个元素中获取键:

keys = data[0].keys

或者如果数据中的哈希值可能会在数据没有意义的情况下省略键,您可以在 data

中获取所有不同的键
keys = data.map(&:keys).flatten.uniq

new_data_array = keys.map { |a| data.map { |d| d[a] } }
=> [["0.4mA", "1A"], ["15w", "5w"]]

new_data_hash = Hash[keys.map {|a| [a, data.map { |d| d[a] }] }]
=> {"current"=>["0.4mA", "1A"], "power"=>["15w", "5w"]}

下面是如何绕过数据数组,直接从一行中的 h1 和 h2 获取值:

Hash[(h1.keys & h2.keys).map {|a| [a, [h1, h2].map { |d| d[a] }] }]
=> {"current"=>["0.4mA", "1A"], "power"=>["15w", "5w"]}

(h1.keys & h2.keys).map {|a| [h1, h2].map { |d| d[a] } }
=> [["0.4mA", "1A"], ["15w", "5w"]]

关于ruby - 遍历 ruby​​ (jekyll) 中的哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com