Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for Array#nitems in Ruby 1.9?

Tags:

arrays

ruby

Ruby 1.8 had a method nitems for arrays. This seems to be gone from Ruby 1.9. Is there a replacement for it in 1.9?


1 Answers

it's been deleted from Ruby 1.9

you can use this instead:

array = [nil, 2, "a", nil, 'b', nil]
array.count{|x| !x.nil?}
 => 3 

or you can re-define it yourself, if your Ruby version doesn't have it anymore:

if ! Array.method_defined?(:nitems)
  class Array
    def nitems
      count{|x| !x.nil?}
    end
  end
end


a = [nil, 2, "a", nil, 'b', nil]
a.nitems
 => 3 
like image 139
Tilo Avatar answered Aug 10 '26 07:08

Tilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!