Frage

This is really strange. When I load a YML file from YAML.load_file and File.open display the same text but the numbers are different. Is this an encoding issue or something? I've never seen this before.

The file is bank.yml

production:
  account_number: 574827192
  routing_number: 048372651

Side note: I changed the numbers in the below file so as to not reveal any actual private data.

UPDATE => I realized the main problem is a result of the leading zero. You cannot have a leading zero in the YAML file or it turns in to an octal. Attempting to figure out how to structure the YAML file to contain leading zeroes.

> irb(main):027:0> YAML.load_file("#{Rails.root}/../../bank.yml")
> => {"production"=>{"account_number"=>574827192, "routing_number"=>847365987}}

> irb(main):028:0> File.open("#{Rails.root}/../../bank.yml").read
> => "production:\n  account_number: 574827192\n  routing_number: 048372651\n"
War es hilfreich?

Lösung

If you wrap the values in your YAML file in quotes, they will then be treated as strings and not drop the leading zero or parse it as octal:

production:
  account_number: '574827192'
  routing_number: '048372651'

Andere Tipps

Yes, when you are doing YAML.load_file, it actually decodes YAML structure and gives you nice hash, which you can readily use.

However, when you do File.open("file.yaml").read, you are reading file in it's raw format, you have to further decode it, to use it as hash or some other data-structure.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top