Forum: Ruby what on earth..

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Joe Van D. (Guest)
on 2006-03-23 04:51
(Received via mailing list)
a = 5
puts  Fixnum == a.class   # spits out true

# spits out "Who knows what I am.  :-("
case a.class
when Fixnum
  puts "I'm a fixnum!"
else
  puts "Who knows what I am.  :-("
end


What's going on here?

Joe
Timothy B. (Guest)
on 2006-03-23 04:59
(Received via mailing list)
case uses === for comparison, not ==

In my irb, Fixnum === 5.class => false

As for why === gives false, I have no idea.  In the mean time, you
could use

case a.class.to_s
when "Fixnum"
    puts ....
else
   puts ....
end

Tim
Mike S. (Guest)
on 2006-03-23 05:00
(Received via mailing list)
On 22-Mar-06, at 9:51 PM, Joe Van D. wrote:

>
>
> What's going on here?

case doesn't use == you can do this:

a = 5

case a
when Fixnum
   puts "I'm a fixnum"
else
   puts "other"
end

and by coincidence (not)

ratdog:~/tmp mike$ irb
irb(main):001:0> a = 5
=> 5
irb(main):002:0> Fixnum === a
=> true

ratdog:~/tmp mike$ ri Module#===
------------------------------------------------------------- Module#===
      mod === obj    => true or false
------------------------------------------------------------------------
      Case Equality---Returns +true+ if _anObject_ is an instance of
      _mod_ or one of _mod_'s descendents. Of limited use for modules,
      but can be used in +case+ statements to classify objects by class.


Hope this helps,

Mike

--

Mike S. <removed_email_address@domain.invalid>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
Timothy B. (Guest)
on 2006-03-23 05:08
(Received via mailing list)
>
> class.
>

Ok, out of the three of us that responded, Mike is the one who knows
what he's talking about most.  Listen to him.

Tim
Joe Van D. (Guest)
on 2006-03-23 05:27
(Received via mailing list)
On 3/22/06, Mike S. <removed_email_address@domain.invalid> wrote:
> > else
> case a
> when Fixnum
>    puts "I'm a fixnum"
> else
>    puts "other"
> end

Very nice, thanks!  Less code is always better.
This topic is locked and can not be replied to.