is there an easy, elegant way to set up a Struct so it has defaults on
initialization?
(besides def initialize?)
···
--
Giles Bowkett
http://www.gilesgoatboy.org
is there an easy, elegant way to set up a Struct so it has defaults on
initialization?
(besides def initialize?)
--
Giles Bowkett
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 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.gilesgoatboy.org
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
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
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.gilesgoatboy.orgNot 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
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.gilesgoatboy.org