What Michael is trying to say: Instead of just checking the type of
said variable (you could have some other object that isn't type
'String' but has same capabilities), check whether or not each
variable's class will respond to the same stimulus, in a sense. This
might be a better solution:
class Array
def elements_respond_to?(method)
self.inject(true) {|same, n| same && n.methods.include?
(method.to_s)}
end
end
# this would allow you to say, "do all elements in this array
implement the method 'to_s'?"
a = ["asdfasdf", 320239, 29309.323, :asdfasf]
a.elements_respond_to?(:to_s) # => true
# especially helpful with array of AR classes, example:
b = [Car.new, Truck.new, Bicycle.new]
b.elements_respond_to?(:horsepower) # => false
On Aug 29, 2006, at 12:44 PM, Michael Genereux wrote:
My concern is that this violates ducktyping. What are you going to do
different with this knowledge?
On 8/29/06, Tom Werner <[EMAIL PROTECTED]> wrote:
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
> [email protected]
> http://lists.sdruby.com/mailman/listinfo/sdruby
>
--
Tom Werner
Helmets to Hardhats
Software Developer
[EMAIL PROTECTED]
www.helmetstohardhats.org
_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby
_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby
_______________________________________________
Sdruby mailing list
[email protected]
http://lists.sdruby.com/mailman/listinfo/sdruby