开发者

Count instances of a value in an array in Ruby 1.8.6

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 e开发者_如何学Crror. Is there a similar method in this version?


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


count = x.select {|e| e == 3}.size


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜