設定をyamlで書いてて、rubyのclassで設定ファイルがなかったらdefalutにベタで書いておいたhashを使うみたいなコード書いてたんだけど、hashのキーをシンボルにしてたのでyamlから読んだ場合まったくみつからないって現象が起きた。
- wrestlername: アントニオ猪木
skill:
- type: 関節技
name: 卍固め
- type: 関節技
name: コブラツイスト
- type: 投技
name: ジャーマンスープレックスホールド
- wrestlername: ジャンボ鶴田
skill:
- type: 関節技
name: 拷問コブラツイスト
- type: 投技
name: バックドロップ
- wrestlername: 三沢光晴
skill:
- type: 関節技
name: フェイスロック
- type: 投技
name: タイガースープレックス'84
こういうyaml書いてシンボルで読むとみつからない。
初心者だとこういうわけのわからないところで普通にハマるので時間があっという間に過ぎる。
require "yaml" require "pp" begin File.open ARGV[0] do |f| YAML.load_documents(f) do |yml| yml.each { |e| pp e[:wrestlername] } end end rescue => e STDERR.puts e end $ ruby yaml.rb test.yml nil nil nil
で、書きなおすのがめんどくさいのでどうにかならないか探したらみつかった。
» RubyのYAMLとシンボルと私 TECHSCORE BLOG
まさにこれで、yamlにシンボル書いてもいけるみたいなんだけどhashie使ってみた。
require "yaml" require "pp" require "hashie" begin File.open ARGV[0] do |f| YAML.load_documents(f) do |yml| yml.each { |e| has = Hashie::Mash.new e pp has[:wrestlername] } end end rescue => e STDERR.puts e end $ ruby yaml2.rb test.yml /Users/ayaseharuka/.rbenv/versions/1.9.3-p385/lib/ruby/gems/1.9.1/gems/hashie-2.0.0/lib/hashie/mash.rb:80: warning: redefining `object_id' may cause serious problems "アントニオ猪木" "ジャンボ鶴田" "三沢光晴"
warning出るけど動く。
mergeされたっぽいので次のバージョンでは直ってると思う。
https://github.com/intridea/hashie/pull/81