Kenji Crosland Kenji Crosland - 1 year ago 83
Ruby Question

String operation in ruby for credit card number

Working on a rails project where there's an order confirmation string with a credit card number with all but the last four digits starred out. What's the proper way to do a string substitution?

What's the operation to get this

credit_card_number = "1111111111111111"

to this?

credit_card_number = "************1111"



Answer Source

If you're using ActiveMerchant, ActiveMerchant::Billing::CreditCard has an instance method called display_number which does this e.g. XXXX-XXXX-XXXX-4338

If you're not, copy activemerchant:

def last_digits(number)    
  number.to_s.length <= 4 ? number : number.to_s.slice(-4..-1) 

def mask(number)

credit_card_number = "1111111111111111"

display_number = mask credit_card_number
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download