Skip to content

Instantly share code, notes, and snippets.

@MrBean83
Last active December 20, 2015 21:59
Show Gist options
  • Select an option

  • Save MrBean83/6201448 to your computer and use it in GitHub Desktop.

Select an option

Save MrBean83/6201448 to your computer and use it in GitHub Desktop.
"Class Warfare, Validate a Credit Card Number"
class CreditCard
def initialize(card_number)
@card = card_number.to_s
if @card.length != 16
raise ArgumentError.new("This is not a valid credit card number.")
end
end
def check_card
chars = @card.split(//)
array = chars.collect! { |x| x.to_i }
double = array.map! { |x| x.even ? x * 2 : x }
double = array.join
double = array.to_s.split(//)
double = double.collect! { |x| x.to_i }
sum = 0
double.each { |x| sum += x }
sum % 10 == 0
end
end
-------------------------------------------------
#This is another iteration I've tried that doesn't seem to work either:
class CreditCard
def initialize(card_number)
@card = card_number.to_s
if @card.length != 16
raise ArgumentError.new("This is not a valid credit card number.")
end
end
def check_card
chars = @card.split(//)
array = chars.collect! { |x| x.to_i }
double = array.each_with_index do |item, index|
if (index % 2 == 0)
array << (item * 2)
else
item = item
end
end
double = array.join
double = array.to_s.split(//)
double = double.collect! { |x| x.to_i }
sum = 0
double.each { |x| sum += x }
sum % 10 == 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment