-----
class Result
def self.[](code)
new(code)
end
def initialize(code)
@code = code
end
def ===(code)
puts '==='
@code == code
end
end
result = Result[:successful]
case result
when :successful
puts 'successful'
else
puts 'unsuccessful'
end
-----
My expected output:
===
successful
But the actual output is:
unsuccessful
My understanding is that case statements use the === function for
comparisons. And in some cases they certainly do (I have seen it work
on other examples). It would appear that in this case the === is not
even being called at all (I tried to pin down what function was being
called, but didn't have much luck).
Could somebody please explain to me why this doesn't work or how one
might fix it?
The === function is called on the object in the when condition, with
the case object as the parameter, not the other way around. It won't
work with the simplified code you've presented, but you'll probably
have to write something like:
result = Result[:successful]
case result
when Result[:successful] then puts 'successful'
else puts 'unsuccessful'
end
--
We develop, watch us RoR, in numbers too big to ignore.
> result = Result[:successful]
>
> case result
> when Result[:successful] then puts 'successful'
> else puts 'unsuccessful'
> end
I figured it could be done this way, but it seemed wasteful to create
a new object instance just to compare against.
Not exactly sure what I want to do with it at present, but this
definately makes it much clearer what is going on.
Thanks for the insight.
Can't do it for the reasons listed above but this looks almost as
pretty
irb(main):002:0> class Result
irb(main):003:1> def self.[](code)
irb(main):004:2> new(code)
irb(main):005:2> end
irb(main):006:1> def initialize(code)
irb(main):007:2> @code = code
irb(main):008:2> end
irb(main):009:1> def to_sym
irb(main):010:2> @code
irb(main):011:2> end
irb(main):012:1> end
=> nil
irb(main):013:0> result = Result[:successfull]
=> #<Result:0x360a88 @code=:successfull>
irb(main):014:0> case result.to_sym
irb(main):015:1> when :successfull
irb(main):016:1> puts 'yay'
irb(main):017:1> else
irb(main):018:1* puts 'nay'
irb(main):019:1> end
yay
=> nil
--
Posted via http://www.ruby-forum.com/.
-----
class Result
attr_reader :code
def self.[](code)
new(code)
end
def initialize(code)
@code = code
end
end
result = Result[:successful]
case result.code
when :successful
puts 'successful'
else
puts 'unsuccessful'
end
-----
Which, as one might expect, gives you:
successful
In any event it is quite good to know the order of operations for
case. I couldn't find anything that described the order and it makes
a big difference when you are comparing objects of different classes.