On Fri, Sep 21, 2012 at 5:50 AM, Eliezer Croitoru <eliezer / ngtech.co.il> wrote:
> I have:
> def initialize(type= nil,location=nil,mode=17)
>
> and the mode can be one of these: 1,4,17,20
> but.. I want that If anyone tries to use other number then these he will get
> exception error.
>
> how would you implement it?
> using raise?
> I was thinking about:
>
> modes = [1, 4, 17, 20]
> raise SyntaxError.new("Modes Allowed: #{modes}") if !modes.index(mode)

I'd use one of

class Foo
  VALID_MODES = [1, 4, 17, 20].freeze
  VALID_MODES = [1, 4, 17, 20].to_set.freeze

  def initialize(type = nil, location = nil, mode = 17)
    raise ArgumentError, "Invalid mode: #{mode.inspect}" unless
VALID_MODES.include? mode
  end

  def initialize(type = nil, location = nil, mode = 17)
    raise ArgumentError, "Invalid mode: %p" % mode unless
VALID_MODES.include? mode
  end

  def initialize(type = nil, location = nil, mode = 17)
    raise ArgumentError, "Invalid mode: %p" % mode unless
VALID_MODES.include? mode
  end
end

The first one is a tad more robust since in case of Array arguments
the second one (which I find nevertheless the most elegant one) will
only report the first element.  The third one is a kind of compromise.

But in any case I'd use a constant for the array or set of valid
modes.  As a variant you could use an integer as bitset:

class Foo
  VALID_MODES = [1, 4, 17, 20].inject(0) {|set, n| set | 1 << n}

  def initialize(type = nil, location = nil, mode = 17)
    raise ArgumentError, "Invalid mode: %p" % [mode] unless
VALID_MODES[mode] == 1
  end
end

Kind regards

robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/