Apr 292011

To have extremely flexible DSLs, I occasionally find myself writing code like this:


if @options.class.name == 'Array'
@options = {'values' => @options}
elsif @options.class.name == 'Hash' && !@options.key?('values')
if @options.key? 'value'
@options['values'] = @options.delete('value')
end
end

Testing object type based on the .class.name string is extremely brittle. For example, what if @options is actually a HashWithIndifferentAccess?

Ruby has a much better method, kind_of?, defined on Object. The main reason kind_of? is better than testing the .class.name string is that kind_of? is aware of class hierarchies.


if @options.kind_of? Array
...