[Sdruby] checking items in array for same class
Tom Werner
tom at helmetstohardhats.org
Tue Aug 29 16:31:34 GMT 2006
Sounds like a good chance to pull that functionality out into a function
for reuse:
class Array
def all_elements_are?(klass)
self.inject(true) { |same, n| same && n.instance_of?(klass) }
end
end
a = ['foo', 'bar', 'baz']
a.all_elements_are?(String) #=> true
b = ['foo', 5, 'baz']
b.all_elements_are?(String) #=> false
Tom
Chris Abad wrote:
> anyone know of a better way to make sure all items in an array are
> instances of the same class? specifically i want to make sure they're
> all instances of the same AR class.
>
> This just doesn't seem the best way:
>
> def method
> object_class = array.first.class
> array.each do | record |
> raise ArgumentError unless record.class == object_class
> end
> end
> _______________________________________________
> Sdruby mailing list
> Sdruby at lists.sdruby.com
> http://lists.sdruby.com/mailman/listinfo/sdruby
>
--
Tom Werner
Helmets to Hardhats
Software Developer
tom at helmetstohardhats.org
www.helmetstohardhats.org
More information about the Sdruby
mailing list