开发者

How can I compare classes in Ruby?

开发者 https://www.devze.com 2023-02-23 00:15 出处:网络
How can I compare classes in Ruby or in other words how can I translate this Java code into Ruby? Class<?> clazz = ...;

How can I compare classes in Ruby or in other words how can I translate this Java code into Ruby?

Class<?> clazz = ...;
if (clazz == String.class) {
  ...
} else if (clazz == Integer.class) {
  ...
}

To clarify: I do not want to compare obj开发者_JAVA技巧ect instances or check if an object is an instance of a class.

EDIT: I do not want to compare object instances or check if an object is an instance of a class, i.e. is_a? and kind_of? don't help me.


The literal translation of your Java code would be something like

klass = ...

if klass == String
  ...
elsif klass == Integer
  ...
end

Or, more idiomatically

klass = ...

case
when klass == String
  ...
when klass == Integer
  ...
end

Or maybe

klass = ...

DISPATCH_TABLE = {
  String => -> { ... },
  Integer => -> { ... }
}

DISPATCH_TABLE[klass].()

However, Ruby is an object-oriented language, and in an object-oriented language this simply doesn't make sense. You would instead just write

class String
  def do_something
    ...
  end
end

class Integer
  def do_something
    ...
  end
end

and the language will perform the dispatching for you. This is called polymorphism and is supported by pretty much every object-oriented language and many non-object-oriented ones as well.

This particular transformation is one of the fundamental Refactorings described in Martin Fowler's book (p. 255), it is called the Replace Conditional With Polymorphism Refactoring.

The biggest problem with providing a sensible solution to your problem is that you don't tell us what the problem is. You only tell us what the solution is. Or, more precisely, you tell us what you think the solution is in Java, and you somehow expect that the solution in Ruby would be exactly 100% identical, even though the languages couldn't be more different.

To provide a good solution, we need to know the problem first. In other words: the most relevant parts of your question are the s


>> "foo".class == "bar".class
true


In Ruby, all classes objects are instances of the Class class. The names of classes are constants that refer to the instance. If you have a reference to the class object, you can compare it with the named constant for that class. So you could do:

if klass == String
  ...
elsif klass == Integer
  ...
end

The expression String.class == Integer.class would be true, since the class of both classes is, of course, Class.

0

精彩评论

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