P
Paul Van Delst
Hello,
The subject line may be confusing as I don't know the correct terminology, so apologies in
advance.
I'm want to be able to create objects, but I want the object creation to only proceed if
the values passed to the init method are in a valid list. E.g.:
class MyObj
VALID_NAMES=['bananas','dog','water']
attr_reader :name, :value
def initialize(name,value)
i=VALID_NAMES.index(name)
if i then
@name,@value=name,value
else
@name,@value=nil
end
end
end
This sorta does what I want, but looks clunky, ugly and quite un-ruby-ish. Is there a
better way (idiom?) to achieve this sort of thing? I.e. is there a way to make the init
method not create even an "empty" object (as happens above) based on the valid names list?
Thanks for any help. (I have about 4 days of Ruby experience so please be kind... )
cheers,
paulv
The subject line may be confusing as I don't know the correct terminology, so apologies in
advance.
I'm want to be able to create objects, but I want the object creation to only proceed if
the values passed to the init method are in a valid list. E.g.:
class MyObj
VALID_NAMES=['bananas','dog','water']
attr_reader :name, :value
def initialize(name,value)
i=VALID_NAMES.index(name)
if i then
@name,@value=name,value
else
@name,@value=nil
end
end
end
This sorta does what I want, but looks clunky, ugly and quite un-ruby-ish. Is there a
better way (idiom?) to achieve this sort of thing? I.e. is there a way to make the init
method not create even an "empty" object (as happens above) based on the valid names list?
Thanks for any help. (I have about 4 days of Ruby experience so please be kind... )
cheers,
paulv