I came to this quiz late, but came up with the following, before
reading the solution, which uses String.tr to do the double and sum
instead of an array.
require 'enumerator'
def luhn(string)
string.scan(/./).reverse.enum_for(:each_with_index).inject(0) do
|sum, (digit, index)|
digit = digit.tr('0123456789', '0246813579') if index % 2 == 1
sum += digit.to_i
end # % 10 == 0
end
After seeing the neat use of each_slice instead of each_with_index
def luhn(string)
string.scan(/./).reverse.enum_for(:each_slice, 2).inject(0) do |sum, (d1, d2)|
sum += d1.to_i + (d2||'0').tr('0123456789', '0246813579').to_i
end % 10 == 0
end
No need to define any extra Enumerator methods.
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/