On Fri, Sep 21, 2012 at 5:50 AM, Eliezer C. [email protected]
wrote:
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