Struct with defaults?

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

(besides def initialize?)

On Nov 16, 2006, at 12:30 PM, Giles B. wrote:

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

(besides def initialize?)


Giles B.
http://www.gilesgoatboy.org

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

On 17.11.2006 00:25, lists wrote:

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

Hi,

At Fri, 17 Nov 2006 03:30:40 +0900,
Giles B. 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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs