0

I've got the following three classes:

class MessageBuilder def initialize(template) @template = template puts @template.instance_of? MessengerTemplate end end class MessengerTemplate def initialize @default_template_id = "111111" end end class JobTemplate < MessengerTemplate def initialize(name) @name = name @template_id = "2222" end end 

I'm trying to check if a parameter passed to MessageBuilder#initialize is an instance of MessengerTemplate. If not, I need to throw an error.

When I call:

message = MessageBuilder.new(JobTemplate.new("Invoice")) 

the following line in the constructor:

puts @template.instance_of? MessengerTemplate 

prints FALSE.

Can someone please tell me what I am doing wrong here?

5
  • Have you tried @template.is_a?(MessengerTemplate)? Commented Jul 31, 2018 at 23:56
  • @jvillian your suggestion does return True. Isn't JobTemplate technically an instance of MessengerTemplate? I know if I did this in Java the instanceOf method would have passed as indicated here: stackoverflow.com/questions/6304056/… Commented Aug 1, 2018 at 0:00
  • Nope. JobTemplate is a subclass of MessengerTemplate. @template is an instance of JobTemplate. Please see answer for details. I don't know nothing about no Java. Commented Aug 1, 2018 at 0:12
  • I suspect you wish to correct the line puts @template.instance_of? MessengerTemplate so that it returns true if @template is an instance of MessengerTemplate or a subclass of MessengerTemplate. If so, please correct the statement of the problem. Commented Aug 1, 2018 at 2:05
  • You have awarded the greenie to an answer that conforms with the interpretation I gave in my comment above. However, you state, "I'm trying to check if a parameter passed to MessageBuilder#initialize is an instance of MessengerTemplate". That is incorrect and needs to be corrected. Commented Aug 1, 2018 at 18:52

1 Answer 1

6

Try:

@template.is_a?(MessengerTemplate) 

As noted in the docs:

Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

MessengerTemplate is a superclass of @template, therefore @template.is_a?(MessengerTemplate) => true.

Sign up to request clarification or add additional context in comments.

2 Comments

...or @template.class <= MessengerTemplate or MessengerTemplate === @template . See See Module#<= and Module#===.
@CarySwoveland exactly. Strictly speaking, Module#<= is the only way to check for requested “is an instance of MessengerTemplate”. is_a? will apparently return true for modules.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.