将YAML转换为哈希数组

时间:2013-11-15 13:51:28

标签: ruby-on-rails ruby-on-rails-4 yaml

所以我有这个permissionrank.yaml文件:

player:
  id: 1
  label: Player
  badge: NIL

bronze helper:
  id: 2
  label: Bronze Helper
  badge: STF_HELP_BRZ

silver helper:
  id: 3
  label: Silver Helper
  badge: STF_HELP_SLV

有没有办法将其加载到哈希的数组中,以便它符合相同格式的Rails'seeds.rb文件?它应输出:

[
  {id: 1, label: "Player",                badge: "NIL"        },
  {id: 2, label: "Bronze Helper",         badge: "STF_HLP_BRZ"},
  {id: 3, label: "Silver Helper",         badge: "STF_HLP_SLV"},
]

这是Rails'种子文件要求的格式。

2 个答案:

答案 0 :(得分:3)

在您的示例中,它从YAML加载,如:

{"player"=>{"id"=>1, "label"=>"Player", "badge"=>"NIL"},
 "bronze helper"=>{"id"=>2, "label"=>"Bronze Helper", "badge"=>"STF_HELP_BRZ"},
 "silver helper"=>{"id"=>3, "label"=>"Silver Helper", "badge"=>"STF_HELP_SLV"}}

所以你真正需要摆脱的是哈希键。如果您只想保留哈希值,可以使用Hash#values方法获得(几乎)所需的数组:

pp YAML.load_file("permissionrank.yml").values

[{"id"=>1, "label"=>"Player", "badge"=>"NIL"},
 {"id"=>2, "label"=>"Bronze Helper", "badge"=>"STF_HELP_BRZ"},
 {"id"=>3, "label"=>"Silver Helper", "badge"=>"STF_HELP_SLV"}]

与您的示例唯一不同的是,这些哈希中的键是字符串,而不是符号。这可能无关紧要,因为Rails通常对此非常放松,但仅仅是为了举例,让我们转换它们。为此,您可以使用ActiveSupport中的Hash#symbolize_keys方法。

pp YAML.load_file("permissionrank.yml").values.map(&:symbolize_keys)

[{id: 1, label: "Player", badge: "NIL"},
 {id: 2, label: "Bronze Helper", badge: "STF_HELP_BRZ"},
 {id: 3, label: "Silver Helper", badge: "STF_HELP_SLV"}]

答案 1 :(得分:0)

下面会给你一系列哈希:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'time': [pd.to_datetime('2016-01-02'),
                            pd.to_datetime('2016-01-03'),
                            pd.to_datetime('2016-01-04')],
                   'value1': [1, 2, 3],
                   'value2': [10, 20, 30]})
df.set_index('time', inplace=True)

fig, ax = plt.subplots(figsize=(30, 15))
ax.plot(df.index, df["value1"], color='black')
ax2 = ax.twinx()
ax2.plot(df.index, df["value2"], color='red')

#axvline stretches nicely
ax.axvline(pd.to_datetime('2016-01-04'), color = 'red',
           alpha = 1,  linestyle = '--')

#vlines stretches nicely
ymin, ymax = ax2.get_ylim()
ax2.set_ylim(ymin, ymax)
ax2.vlines([pd.to_datetime('2016-01-02'), pd.to_datetime('2016-01-03')],
           ymin=ymin, ymax=ymax, color='blue', linestyle='-')

plt.show()