Skip to content

Instantly share code, notes, and snippets.

@markgarrigan
Last active March 8, 2019 09:11
Show Gist options
  • Select an option

  • Save markgarrigan/9eee539b337b588703b5e092fd16912a to your computer and use it in GitHub Desktop.

Select an option

Save markgarrigan/9eee539b337b588703b5e092fd16912a to your computer and use it in GitHub Desktop.
Luhn Validator
class Luhn
def self.valid?(string)
transformed = string.gsub(/ /,'') #Remove spaces
return false if transformed.length < 1 #Return false if length less than 1
return false if transformed.match?(/\D/) #Return false if any non digit characters
# Reverse the string Scan for 2 capture groups
transformed = transformed.reverse.scan(/(.)(.)/).each do |pair|
# Turn both items into integers
pair[0] = pair[0].to_i
pair[1] = pair[1].to_i
# Double the last item
transform = pair[1] * 2
# If the doubled result is greater than 9 subtract 9
pair[1] = transform > 9 ? transform - 9 : transform
end
# Flatten out the array, sum the items and check if its divisibleb by 10
transformed.flatten.inject(:+)%10 == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment