-1

I have rails app with models Car and Wheel. And I have the method which returns an array of different objects. e.g.

array = [Car.new, Car.new, Wheel.new, Wheel.new, 'home', 'market', 'fun']

How to count Car instances and Wheel instances in an array?

I tried array.include?(Car) and array.count(Car) and they didn't work.

Stefan
  • 109,145
  • 14
  • 143
  • 218

3 Answers3

7

You can use Enumerable#grep to fetch the instances of Car:

array.grep(Car).size
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
2

you can do like below for counting Car instance:

array.count { |e| e.instance_of? Car} 

or instead of instance_of? you can use kind_of? if that sounds better.

Sajan
  • 1,893
  • 2
  • 19
  • 39
2

kind_of? and is_a? are synonymous. They are Ruby's equivalent to Java's instanceof.

instance_of? is different in that it only returns true if the object is an instance of that exact class, not a subclass

array.count { |e| e.instance_of? Car} 

For more details: kind_of? vs is_a? vs instance_of?

Community
  • 1
  • 1
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55