Skip to content

Instantly share code, notes, and snippets.

@loriculberson
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save loriculberson/e4f5bf8f661eb776ad73 to your computer and use it in GitHub Desktop.

Select an option

Save loriculberson/e4f5bf8f661eb776ad73 to your computer and use it in GitHub Desktop.
card_number = "342801633855673"
credit_card = card_number.chars.map(&:to_i).reverse
double_index = credit_card.select.with_index { |_,i| i.odd? }
products = double_index.map {|num| num * 2 }
doubled_sum = products.map {|digits| digits.to_s.split('')}.map{|pair| pair.reduce(0) {|sum, x| sum + x.to_i}}.reduce(:+)
product_sum = credit_card.select.with_index { |_,i| i.even? }.reduce(:+)
total_sum = doubled_sum + product_sum
if total_sum % 10 == 0
puts "The card number #{card_number} is valid. Let's go shopping!"
else
puts "The card number #{card_number} is invalid. Sorry!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment