Newbie Q: conditional object creation

Paul Van Delst wrote:

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

just:

@name,@value=name,value if VALID_NAMES.index(name)

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?

any not initialized instance variable will return null, so just don't bother ;D

lopex

Marcin Mielżyński wrote:

Paul Van Delst wrote:

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

just:

@name,@value=name,value if VALID_NAMES.index(name)

Excellent! Thanks very much.

cheers,

paulv

···

--
Paul van Delst Ride lots.
CIMSS @ NOAA/NCEP/EMC Eddy Merckx