0

So I have this test script

require 'yaml'

hashYaml = YAML::load_file("./monFichier.yaml")
puts "hashYaml : " 
puts hashYaml

hashManuel = {enonce: "ma question", titre: "mon titre" } 
puts "hashManuel : "
puts hashManuel

where ./monFichier.yaml contains the following lines :

- enonce: "ma question"
  titre: "mon titre" 

and the output is :

hashYaml : 
{"enonce"=>"ma question", "titre"=>"mon titre"}
hashManuel : 
{:enonce=>"ma question", :titre=>"mon titre"}

Can somebody please explain

  1. why both lines are different ?
  2. how I could obtain hashYaml in the same format as hashManuel ?

Cheers,

marsupilam
  • 127
  • 2
  • 7

1 Answers1

0

So I found this answer, which I checked to be working.

It is to edit the Yaml file as follows :

- :enonce: "ma question"
  :titre: "mon titre" 

Is there an other way that does not involve modifying my yaml file ? Yes, see below

Edit : the answer I was looking for

Adapted from this post

So my Yaml file defines a table of hashes in Ruby. Say, it reads :

- enonce: "ma question facile"
  titre: "mon titre clair" 
- enonce: "ma question dure"
  titre: "mon titre obscur" 

To import this file in Ruby as list of hashes whose keys are symbols, ie {:myKey => "itsValue"} (what I meant by a proper hash before I knew the vocab) one may proceed as follows :

require 'yaml'

hashYaml = YAML::load_file('./monFichier.yaml')

hashYaml.each do |currentHash| # I am really working with a table of hash(es)
  currentHash.keys.each do |key|
    currentHash[(key.to_sym rescue key) || key] = currentHash.delete(key)
  end
end

Cheers,

Community
  • 1
  • 1
marsupilam
  • 127
  • 2
  • 7
  • Probably noteworthy that the inverse function to `YAML::load`, which is `YAML::dump` outputs the `:key: itsValue` convention in Yaml. This would push towards the first solution : editing the source Yaml file so as to have it consist of `:key: itsValue` assignments – marsupilam Jul 16 '16 at 16:50