Home » Ruby » Count instances of a value in an array in Ruby 1.8.6

Count instances of a value in an array in Ruby 1.8.6

Posted by: admin December 31, 2017 Leave a comment

Questions:

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?

Answers:

As a general tip: there is the really cool backports library by Marc-André Lafortune, which tries to implement as much of the new features of the Ruby 1.8.7, 1.8.8 (i.e. the tip of the 1_8 branch in the Subversion repository), 1.9.1 and 1.9.2 standard libraries as well as some select methods from ActiveSupport as possible in pure, cross-1.8-1.9-compatible Ruby.

So, if you just do

require 'backports'

it will turn your Ruby 1.8.6, 1.8.7 or 1.9.1 into as close to Ruby 1.9.2 as is possible without dropping to C or breaking backwards compatibility.

Disclaimer: I haven’t actually used it myself, since I don’t see the point of using an outdated version of Ruby anyway.

Questions:
Answers:
x = [3,4,5,6,7,78,4,3,2,5,5,3]
x.grep(3).size
#=> 3

Questions:
Answers:
count = x.select {|e| e == 3}.size