Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count instances of a value in an array in Ruby 1.8.6

Tags:

arrays

ruby

The following line is working fine in ruby 1.8.7 and not in 1.8.6. What alternative I can use in 1.8.6

x = [3,4,5,6,7,78,4,3,2,5,5,3]
x.count(3)
=> 3

Since count is not a method in Array in version 1.8.6, I am getting this error. Is there a similar method in this version?

like image 262
bragboy Avatar asked Feb 04 '11 11:02

bragboy


2 Answers

x = [3,4,5,6,7,78,4,3,2,5,5,3]
x.grep(3).size
#=> 3
like image 125
Michael Kohl Avatar answered Sep 17 '22 14:09

Michael Kohl


count = x.select {|e| e == 3}.size
like image 27
Geo Avatar answered Sep 21 '22 14:09

Geo