user762579
user762579

Reputation:

YAML read should be an Hash not an Array, what's wrong?

I am reading a YAML file:

listing = YAML.load_file(File.expand_path(....)

I try to iterate on the listing items on build an OpenStructure

items = Array.new
listing.each do |item|
  items << OpenStruct.new(item)
end

But it's raising an error:

undefined method `each_pair' for ["item1", "label1"]:Array (NoMethodError)

My test YAML file is:

item1: label1
item2: label2

What am I doing wrong?

Upvotes: 0

Views: 540

Answers (1)

gregates
gregates

Reputation: 6714

The error is occuring in the OpenStruct initializer.

When you call Hash#each and give it a block with arity = 1, the block gets an array like [key, value]. Then you're passing that to OpenStruct.new, which results in an error since you can't initialize an OpenStruct with an Array.

What I think you want is:

listing.each do |key, value|
  items << OpenStruct.new({ key: value })
end

alternatively, the yaml file could be

- item1: label1
- item2: label2

and I believe the code would work as is.

The YAML file you have is deserialized to:

{ item1: "label1", item2: "label2" }

whereas the one I've described would be:

[{ item1: "label1" }, { item2: "label2" }]

Upvotes: 1

Related Questions