0

I can't undestand. What is Test1 in the following example?:

class Test1 def request Test2.new.get_request(self.class) end end class Test2 def get_request(klass) p klass # => Test1 case klass when Test1 p 'Test1 is class' when "Test1" p 'Test1 is string' when :Test1 p 'Test1 is sybol' else p 'wtf is klass ????' end end end Test1.new.request # Test1 # "wtf is klass ????" 

(It works if self.class change to self) But what is explanation of this behavior?

2 Answers 2

2

The explanation is that in case of CASE statement the comparison the check is a === where as in if it is ==. SO if you had

p "GOT IT" if klass == Test1

It would have worked, where as doing

p "GOT IT" if klass === Test1

Will not yield the print statment.

In short the comparison is done by comparing the object in the when-clause with the object in the case-clause using the === operator and not == hence the TEST1 value in klass variable does not compare with === (case stmt).

To add more clarity to this case :

1.8.7 :074 > Test1.new.class == Test1 => true 1.8.7 :075 > Test1.new.class === Test1 => false 

Second one happens for case/when statement

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

1 Comment

The comparison is done the other way round, i.e. Test1 === Test1.new.class. Passing an instance (i.e. self instead of self.class) works as expected: Test1 === Test1.new is true
2

In a case expression, the when-clauses are compared to the case value with the === operator. It is equivalent to this:

if Test1 === klass p 'Test1 is class' elsif "Test1" === klass p 'Test1 is string' elseif :Test1 === klass p 'Test1 is sybol' else p 'wtf is klass ????' end 

The reason it doesn't work the way you want is because Class#=== is implemented to test whether the right operand is an instance of the class. It's meant to make it convenient to do case expressions based on the class of an object. But here it falls down, because you're not actually trying to determine the object's class. Since Test1 isn't an instance of itself — it's an instance of Class — that test yields false.

I think the best you'll get if you actually need to test class identity in a case expression is something like when ->k{ k == Test1 }, but it's just kind of an awkward case for the language.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.