Array of Types in Ruby
I am trying to create instances of objects of various types by iterating and checking for validity. I need an array of types so I can do something like this:
def tryClasses(in)
types = [Foo::A, Foo::B, Foo::C]
types.each do |type|
a = type.new(in)
return开发者_开发问答 a != null
end
end
How do I create and array of class types? Doing it this way I am getting a NoMethodError (undefined method 'A' for Foo)
Apart from the obvious syntactic errors (e.g. in
is a reseved word, and null
is spelled nil
in Ruby), the code you showed should work just fine as it is, and indeed it does when I copy&paste it into my Ruby installation. This assumes, of course, that the classes Foo::A
, Foo::B
and Foo::C
actually exist. If they don't, then the code obviously cannot possibly work.
It is, however, completely un-Rubyish and violates just about every coding convention in the book:
- indentation is 2 spaces
- method names are
snake_case
, notcamelCase
- explicitly checking for equality to
nil
is a no-no, simply calling#nil?
is much preferred try_classes
isn't exactly an intention-revealing method name- and WTF does
in
mean? - Rubyists much prefer higher-order methods over explicit looping
Here's a more Rubyish version of the code you wrote:
def can_create_object?(*args)
[Foo::A, Foo::B, Foo::C].none? do |klass|
klass.new(*args).nil?
end
end
However, note that I am pretty convinced that the whole idea is fundamentally flawed.
精彩评论