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 object 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
Or, more idiomatically
Or maybe
However, Ruby is an object-oriented language, and in an object-oriented language this simply doesn’t make sense. You would instead just write
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