Typos in eigenclass - Changes in Ruby 1.9

Moin, moin!

I didn't find a way to post this in http://eigenclass.org, so I put it
here.

In http://eigenclass.org/hiki.rb?Changes+in+Ruby+1.9#l54
(Enumerable#count) the following code was listed:

def count(*a)
  inject(0) do |c, e|
    unless a.size == 1 # suspect, but this is how it works
      (a[0] == x) ? c + 1 : c
    else
      yield(x) ? c + 1 : c
    end
  end
end

with the expected result:

["bar", 1, "foo", 2].count(1) # => 1
["bar", 1, "foo", 2].count{|x| x.to_i != 0} # => 2

This doesn't work, because of the variable "x" and "unless" instead of
"if". After the following changes it works as expected:

module Enumerable
  def count(*a)
    inject(0) do |c, e|
      if a.size == 1
        (a[0] == e) ? c + 1 : c
      else
        yield(e) ? c + 1 : c
      end
    end
  end
end

p ["bar", 1, "foo", 2].count(1) # => 1
p ["bar", 1, "foo", 2].count{|x| x.to_i != 0} # => 2

Wolfgang Nádasi-Donner

···

--
Posted via http://www.ruby-forum.com/.