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.
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2006-03-23 03: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
24d3102d656a4654db23d28382a2d6f0?d=identicon&s=25 Timothy Bennett (Guest)
on 2006-03-23 03: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
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2006-03-23 04:00
(Received via mailing list)
On 22-Mar-06, at 9:51 PM, Joe Van Dyk 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 Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
24d3102d656a4654db23d28382a2d6f0?d=identicon&s=25 Timothy Bennett (Guest)
on 2006-03-23 04: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
38a8230ed3d5c685558b4f0aad3fc74b?d=identicon&s=25 Joe Van Dyk (Guest)
on 2006-03-23 04:27
(Received via mailing list)
On 3/22/06, Mike Stok <mike@stok.ca> 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.