How to pass JSON values into Struct Ruby object?
ruby
Solution
Try using:
a = A.new(*JSON[json].values)
a.class # => A < #<Class:0x00000102955828>
The problem is that `values` returns an array, but you need the individual elements of the array. Using `*` "splats" the array back into its components, which makes Struct happy when you pass the values to `new`.
EDIT:
This will fail if the ordering of the JSON and the Struct do not match!
This forces the order of the values.
a = A.new(*JSON[json].values_at('a', 'b'))
{
:a => 1,
:b => 2
}
a.class # => A < #<Class:0x00000102955828>
JSON preserves the hash insertion order, as does Ruby, so, JSON rendered and parsed by Ruby will be correct. JSON rendered by something that doesn't preserve the order could be a problem, but `values_at` fixes the problem.
Note that JSON converts symbols to strings, so the keys passed to `values_at` have to be strings, not symbols.
Problem
Given a JSON object ``` {"a": 1, "b":2} ``` and a value object that is derived from a struct: ``` class A < Stuct.new(:a, :b) end ``` How would I make an instance of A that has the values from the JSON? I am trying: ``` a = A.new(JSON.parse({a:1,b:2}.to_json).values) => #<struct A a=[1, 2], b=nil> ``` But I would expect a->1, and b->2