Wednesday, June 29, 2011

Case switch statements

Thanks to my boss, I learned something I'd forgotten (more evidence for the wisdom of this blog) about the case statement. Here's my code:
case arr_of_structs.first[attribute]
when Float, Fixnum
out.puts "@attribute #{attribute} NUMERIC"
when String
out.puts "@attribute #{attribute} STRING"
when Array
out.puts "@attribute charges relational"
2.0.step(12, 0.5).each do |ph|
out.puts "@attribute charge_at_#{ph} NUMERIC"
end #ph.each do
out.puts "@end charges"
end #case
end # each do

This was failing because I had previously been comparing the .class of the attribute value to the string versions of each class name. This wasn't working, and that becomes clear when I was reminded that case uses the === operator for comparison. I don't really understand all the ramifications, but it is kinda explained here: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html

No comments:

Post a Comment