In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:
irb(main):001:0> case Integer
irb(main):002:1> when String then 'str’
irb(main):003:1> when Integer then 'int’
irb(main):004:1> when Array then 'arr’
irb(main):005:1> else '???'
irb(main):006:1> end
=> “???”
Any ideas, other than `if … elsif … elsif … else’? Is there any way to
make case use == instead of ===? Or something?
In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:
irb(main):001:0> case Integer
irb(main):002:1> when String then ‘str’
irb(main):003:1> when Integer then ‘int’
irb(main):004:1> when Array then ‘arr’
irb(main):005:1> else ‘???’
irb(main):006:1> end
=> “???”
It’s because the more common use is to compare objects with their
classes:
case 1
when Integer then ‘int’
…
end
Any ideas, other than `if … elsif … elsif … else’? Is there any
way to
make case use == instead of ===? Or something?
In general, I love the way case statement matching works. I’m having
trouble, however, when trying this:
irb(main):001:0> case Integer
irb(main):002:1> when String then ‘str’
irb(main):003:1> when Integer then ‘int’
irb(main):004:1> when Array then ‘arr’
irb(main):005:1> else ‘???’
irb(main):006:1> end
=> “???”
It’s because the more common use is to compare objects with their
classes:
case 1
when Integer then ‘int’
…
end
Any ideas, other than `if … elsif … elsif … else’? Is there any
way to
make case use == instead of ===? Or something?
Oh, I know why it does what it does, and I love it the way it is.
How about using a Hash:
Well, that was a smaller example. I suppose I could use a hash and bind
classes to procs… but I have since come up with this (somewhat ugly)
trick:
irb(main):001:0> case Integer.id
irb(main):002:1> when String.id then 'str’
irb(main):003:1> when Integer.id then 'int’
irb(main):004:1> when Array.id then 'arr’
irb(main):005:1> else '???'
irb(main):006:1> end
=> “int”