Created
May 30, 2015 13:18
-
-
Save kamigerami/1ad72078b63d49f020d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/ruby | |
| # CS50 Harvard PSET 1 - Bad Credit in Ruby. | |
| prompt = "Please enter a valid CC number : " | |
| input = nil # initialize the variable so you can invoke methods on it | |
| input_array = Array.new | |
| input_add = Array.new | |
| type_of_card = nil | |
| loop do | |
| puts "#{prompt}" | |
| input = Integer(gets) rescue nil | |
| if input.to_s.length < 13 || input.to_s.length > 16 || input.is_a?(String) | |
| puts "input wrong -> minimum 13 and max 16 digits only" | |
| else | |
| puts "validating your input : #{input}" | |
| if input.to_s =~ /^4/ | |
| type_of_card = "VISA" | |
| elsif input.to_s =~ /^5[0-5]/ | |
| type_of_card = "MASTERCARD" | |
| elsif input.to_s =~ /^34|^37/ | |
| type_of_card = "AMEX" | |
| else | |
| type_of_card = "INVALID" | |
| end | |
| break | |
| end | |
| end | |
| #add the input into an array | |
| input_array = input.to_s.split('') | |
| #Multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products' digits together. | |
| input_every_other = (0... input_array.length).select{ |x| x%2 == 2-1 }.map { |y| input_array[y] } | |
| input_add = input_every_other.collect { |x| x.to_i*2 } | |
| # split every integer into a new array index | |
| #input_add = input_add.to_s.split(',') | |
| input_add = input_add.join.chars.map(&:to_i) | |
| input_sum = input_add.inject(:+) | |
| #Now let’s add that sum (27) to the sum of the digits that weren’t multiplied by 2: | |
| input_the_rest = (0... input_array.length).select{ |x| x%2 == 1-1 }.map { |y| input_array[y] } | |
| input_the_rest << input_sum | |
| #convert to integer | |
| input_the_rest = input_the_rest.map(&:to_i) | |
| if input_the_rest.inject(:+)%10 == 0 | |
| puts "#{type_of_card}" | |
| else | |
| puts "#{type_of_card = 'INVALID'}" | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment