Initializing a Struct from an array

I'm writing some code to dump database tables into in-memory hashtables.
Here's an example:

Foo = Struct.new('Foo', :id, :a, :b, :c)
conn.select_all('select * from foo').each do |h|
current = Foo.new(h[0], h[1], h[2], h[3])
@foo_map[current.id <http://current.id>] = current
end

It's the Foo.new ... part that bugs me. Is there a nice clean way of
initializing a Struct from an array?

Thanks
-John
http://www.iunknown.com

John Lam wrote:

I'm writing some code to dump database tables into in-memory hashtables.
Here's an example:

Foo = Struct.new('Foo', :id, :a, :b, :c)
conn.select_all('select * from foo').each do |h|
current = Foo.new(h[0], h[1], h[2], h[3])
@foo_map[current.id <http://current.id>] = current
end

It's the Foo.new ... part that bugs me. Is there a nice clean way of
initializing a Struct from an array?

current = Foo.new(*h)

Foo.new(*h)

generally

irb(main):002:0* def t(a, b = nil, c = nil)
irb(main):003:1> p [a,b,c]
irb(main):004:1> end
=> nil
irb(main):005:0>
irb(main):006:0* t(1)
[1, nil, nil]
=> nil
irb(main):007:0> t(1,2,3)
[1, 2, 3]
=> nil
irb(main):008:0> t([1,2,3])
[[1, 2, 3], nil, nil]
=> nil
irb(main):009:0> t(*[1,2,3])
[1, 2, 3]
=> nil

hth,

brian

···

On 27/10/05, John Lam <drjflam@gmail.com> wrote:

I'm writing some code to dump database tables into in-memory hashtables.
Here's an example:

Foo = Struct.new('Foo', :id, :a, :b, :c)
conn.select_all('select * from foo').each do |h|
current = Foo.new(h[0], h[1], h[2], h[3])
@foo_map[current.id <http://current.id>] = current
end

It's the Foo.new ... part that bugs me. Is there a nice clean way of
initializing a Struct from an array?

Thanks
-John
http://www.iunknown.com

--
http://ruby.brian-schroeder.de/

Stringed instrument chords: http://chordlist.brian-schroeder.de/

Thanks, guys!

John Lam wrote:

Thanks, guys!

Additional recommendation: don't do "select *" in production code, always
explicitely query those columns you need. Why? If there are changes your
code will still work but since the order and number of fields read by
"select *" is not fixed you risk later errors that even may go undetected
for a while.

Kind regards

    robert