The Luhn algorithm

These two functions implement the Luhn algorithm, which is used to validate various identification numbers, such as credit card numbers.

Pick the solution you think is best, and explain why.

Solution A
def luhn(card_no)
  card_no.split("")
    .reverse
    .each_with_index
    .map {|x, i| i.odd? and x.to_i * 2 or x.to_i}
    .map {|x| if x.to_s.length > 1; x.to_s.split("").map(&:to_i).inject(:+); else x end}
    .inject(:+) % 10 == 0
end
 
Solution B
def luhn(card_no)
  card_no
    .chars
    .reverse
    .each_slice(2)
    .inject(0) do |sum, (a, b)|
      double = b.to_i * 2
      sum + a.to_i + (double > 9 ? double - 9 : double)
    end % 10 == 0
end
 
Log in to accept this challenge
Submitted by others
  • B -- 172 chars vs 218