struct with defaults?

G

Giles Bowkett

is there an easy, elegant way to set up a Struct so it has defaults on
initialization?

(besides def initialize?)
 
L

lists

is there an easy, elegant way to set up a Struct so it has defaults on
initialization?

(besides def initialize?)

Not an exact answer to your question, but would using OpenStruct fit
the bill?

#!/usr/bin/env ruby

require 'ostruct'

user = OpenStruct.new({:name => 'Bob', :uid => 1234})
p user.name
p user.uid
user.name = 'Fred'
p user.name
 
R

Robert Klemme

Not an exact answer to your question, but would using OpenStruct fit the
bill?

#!/usr/bin/env ruby

require 'ostruct'

user = OpenStruct.new({:name => 'Bob', :uid => 1234})
p user.name
p user.uid
user.name = 'Fred'
p user.name

This just fills an instance with values. You would have to encapsulate
that in a method like

def create() OpenStruct.new:)name => 'Bob', :uid => 1234) end

to match the OP's requirements. That can also be done with a Struct

S = Struct.new:)name, :uid)
def S.create() new('Bob', 1234) end

irb(main):003:0> S.create
=> #<struct S name="Bob", uid=1234>

Kind regards

robert
 
N

Nobuyoshi Nakada

Hi,

At Fri, 17 Nov 2006 03:30:40 +0900,
Giles Bowkett wrote in [ruby-talk:225339]:
is there an easy, elegant way to set up a Struct so it has defaults on
initialization?

(besides def initialize?)

class User < Struct.new:)name, :uid)
def initialize(name = 'Bob', uid = 1234)
super
end
end
 
G

Giles Bowkett

that is easy and elegant! exactly as requested -- thank you!

Hi,

At Fri, 17 Nov 2006 03:30:40 +0900,
Giles Bowkett wrote in [ruby-talk:225339]:
is there an easy, elegant way to set up a Struct so it has defaults on
initialization?

(besides def initialize?)

class User < Struct.new:)name, :uid)
def initialize(name = 'Bob', uid = 1234)
super
end
end
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top