Typos in eigenclass - Changes in Ruby 1.9

  • Thread starter Wolfgang Nádasi-donner
  • Start date
W

Wolfgang Nádasi-donner

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top