-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
  • 102,972
  • 12
  • 132
  • 203

3 Answers3

7

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

array.grep(Car).size
ndnenkov
  • 34,386
  • 9
  • 72
  • 100
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,804
  • 2
  • 21
  • 34
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
  • 9,916
  • 1
  • 27
  • 54