[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

struct with defaults?

Giles Bowkett

11/16/2006 6:31:00 PM

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

(besides def initialize?)

--
Giles Bowkett
http://www.gilesg...

4 Answers

lists

11/16/2006 11:26:00 PM

0

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

> is there an easy, elegant way to set up a Struct so it has defaults on
> initialization?
>
> (besides def initialize?)
>
> --
> Giles Bowkett
> http://www.gilesg...
>
>

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

Robert Klemme

11/17/2006 9:25:00 AM

0

On 17.11.2006 00:25, lists wrote:
> On Nov 16, 2006, at 12:30 PM, Giles Bowkett wrote:
>
>> is there an easy, elegant way to set up a Struct so it has defaults on
>> initialization?
>>
>> (besides def initialize?)
>>
>> -- Giles Bowkett
>> http://www.gilesg...
>>
>>
>
> 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

Nobuyoshi Nakada

11/17/2006 10:51:00 AM

0

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

--
Nobu Nakada

Giles Bowkett

11/17/2006 6:58:00 PM

0

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

On 11/17/06, Nobuyoshi Nakada <nobu@ruby-lang.org> wrote:
> 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
>
> --
> Nobu Nakada
>
>


--
Giles Bowkett
http://www.gilesg...