Skip to content

Instantly share code, notes, and snippets.

@nlprater
Last active December 19, 2015 04:09
Show Gist options
  • Save nlprater/5895239 to your computer and use it in GitHub Desktop.
Save nlprater/5895239 to your computer and use it in GitHub Desktop.
Exercise: Class Warfare, Validate a Credit Card Number
class CreditCard
def initialize(num)
if num.to_s.length == 16
@num = num
else
raise ArgumentError.new("Invalid number length.")
end
end
def sum_of_odds
num_array = Array.new
num_hash = Hash.new
odd_array = Array.new
@num.to_s.each_char {|c| num_array.push(c.to_i)}
puts num_array.inspect
num_array.each_index {|i| num_hash[i] = num_array[i]}
puts num_hash
num_hash = num_hash.select! {|k,v| k == 0 || k % 2 == 0}
puts num_hash.inspect
num_hash.each_pair {|k,v| num_hash[k] = v * 2}
puts num_hash.inspect
num_hash.each_pair {|k,v| odd_array.push(num_hash[k])}
puts odd_array.inspect
odd_array.each_index { |i|
odd_array[i].to_s.each_char {|c| odd_array.push(c.to_i) if odd_array[i] > 9}
}
puts odd_array.inspect
odd_array.delete_if {|e| e > 9}
puts odd_array.inspect
@odd_sum = odd_array.inject(:+)
end
def sum_of_evens
num_array = Array.new
num_hash = Hash.new
even_array = Array.new
@num.to_s.each_char {|c| num_array.push(c.to_i)}
puts num_array.inspect
num_array.each_index {|i| num_hash[i] = num_array[i]}
puts num_hash.inspect
num_hash = num_hash.select! {|k,v| k != 0 && k % 2 != 0}
puts num_hash.inspect
num_hash.each_pair {|k,v| even_array.push(num_hash[k])}
puts even_array.inspect
@even_sum = even_array.inject(:+)
end
def check_card
(sum_of_odds + sum_of_evens) % 10 == 0 ? true : false
puts (@even_sum + @odd_sum)
end
end
visa = CreditCard.new(8769345123245673)
visa.check_card
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment