Initializing a Struct from an array

J

John Lam

------=_Part_4331_20153101.1130431923854
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

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

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

------=_Part_4331_20153101.1130431923854--
 
J

Jamey Cribbs

John said:
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)
 
B

Brian Schröder

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

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

Foo.new(*h)

generally

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

hth,

brian
 
J

John Lam

------=_Part_4583_8957989.1130432393006
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

Thanks, guys!

------=_Part_4583_8957989.1130432393006--
 
R

Robert Klemme

John said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top