开发者

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:

  1. indentation is 2 spaces
  2. method names are snake_case, not camelCase
  3. explicitly checking for equality to nil is a no-no, simply calling #nil? is much preferred
  4. try_classes isn't exactly an intention-revealing method name
  5. and WTF does in mean?
  6. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜