0

I have a custom class Region, which I instantiated as following : node = Region.new

I wonder what is the differences, and why the following conditions act like that :

puts node.class === Region         # => false
puts node.class == Region          # => true
puts node.is_a?(Region)            # => true
puts node.class.to_s === 'Region'  # => true

What is the best way to test (ideally, in a case condition) what is the class of my node (as it could be classes like Country or Site as well...)

Thank you for your time :)

  • Does this anwer your question? https://stackoverflow.com/questions/3424782/how-do-i-check-if-a-variable-is-an-instance-of-a-class – thiebo Jul 04 '22 at 12:44
  • Warning: I lack context to give a more concrete opinion, but this sounds like poor code design. Doing a `case` statement on a `class` *usually* means you're failing to make proper use of OOP. – Tom Lord Jul 04 '22 at 13:39
  • For example, could you define the same method name on `Region`, `Country` and `Site`, but have different implementations? Then you could call, say, `node.area` and have the implementation detail encapsulated within the class, instead of putting it in your case statement? – Tom Lord Jul 04 '22 at 13:40

1 Answers1

3

In a case block you can do:

case node
when Region
  # node is an instance of Region 
else
  # node is not an instance of Region
end

Which would internally check the condition in this order: Region === node. For details about the === method read this answer.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Ok clear thank you, case test is like a `===`, but i got another question : why is `case node.class ....` a bad way to write a case condition ? – louisgreiner Jul 04 '22 at 13:18
  • `# node is an instance of Region` -- `node` is kind of `Region` – mechnicov Jul 04 '22 at 13:20
  • @louisgreiner `case node.class` along with `when Region` simply won’t work because `Region === Region` is false. – Stefan Jul 05 '22 at 06:30