Your variable newarray
is named oddly, since in Ruby and most other languages, arrays are indexed by integers, not random Objects like Class
. It's more likely this is a Hash
.
Also, you should be using c.class
, instead of c.type
, which is deprecated.
Finally, since you're creating a Hash
, you can use inject
like so:
newarray = array.inject( {} ) do |h,c|
h[c.class] = h.key?(c.class) ? h[c.class]+1 : 0
h
end
Or, for a one-liner:
newarray = array.inject( {} ) { |h,c| h[c.class] = h.key?(c.class) ? h[c.class]+1 : 0 ; h }
As you can see, this gives the desired results:
irb(main):001:0> array = [1, {}, 42, [], Object.new(), [1, 2, 3]]
=> [1, {}, 42, [], #<Object:0x287030>, [1, 2, 3]]
irb(main):002:0> newarray = array.inject( {} ) { |h,c| h[c.class] = h.key?(c.class) ? h[c.class]+1 : 0 ; h }
=> {Object=>0, Hash=>0, Array=>1, Fixnum=>1}