C
cremes.devlist
I've been using ruby for several months now so imagine my surprise when I wrote something using the 'case' construct and I discovered that I didn't understand how to use it! What's worse is that even after looking through the Pickaxe and some code "in the wild" that uses 'case' I still don't see what I'm doing wrong.
Here's the code in question:
def case_test(obj)
print "testing via case... "
case obj.class
when Array
puts "obj is a #{obj.class}"
when String
puts "obj is a #{obj.class}"
else
puts "obj is unknown: #{obj.class}"
end
end
def if_test(obj)
print "testing via if... "
klass = obj.class
if klass == Array
puts "obj is a #{klass}"
elsif klass == String
puts "obj is a #{klass}"
else
puts "obj is unknown: #{obj.class}"
end
end
case_test(Array.new)
if_test(Array.new)
case_test(String.new)
if_test(String.new)
case_test(Hash.new)
if_test(Hash.new)
cremes$ ruby a.rb
testing via case... obj is unknown: Array
testing via if... obj is a Array
testing via case... obj is unknown: String
testing via if... obj is a String
testing via case... obj is unknown: Hash
testing via if... obj is unknown: Hash
What am I doing wrong here?
Here's the code in question:
def case_test(obj)
print "testing via case... "
case obj.class
when Array
puts "obj is a #{obj.class}"
when String
puts "obj is a #{obj.class}"
else
puts "obj is unknown: #{obj.class}"
end
end
def if_test(obj)
print "testing via if... "
klass = obj.class
if klass == Array
puts "obj is a #{klass}"
elsif klass == String
puts "obj is a #{klass}"
else
puts "obj is unknown: #{obj.class}"
end
end
case_test(Array.new)
if_test(Array.new)
case_test(String.new)
if_test(String.new)
case_test(Hash.new)
if_test(Hash.new)
cremes$ ruby a.rb
testing via case... obj is unknown: Array
testing via if... obj is a Array
testing via case... obj is unknown: String
testing via if... obj is a String
testing via case... obj is unknown: Hash
testing via if... obj is unknown: Hash
What am I doing wrong here?