views:

217

answers:

2

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"

Thanks,

Kenji

+1  A: 

There isn't a 'proper' way, but I quite like regex so I might do this:

x.gsub!(/.(?=....)/, '*')

A more conventional way would be this:

x = '*' * (x.size - 4) + x[-4, 4]
Mark Byers
+2  A: 

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) 
end

def mask(number)
 "XXXX-XXXX-XXXX-#{last_digits(number)}"
end

credit_card_number = "1111111111111111"

display_number = mask credit_card_number
Steve Graham
Thanks a lot, Steve!I am using Active Merchant but for some reason my order object couldn't access the display number method. Your method did work nonetheless. Thanks for the help!
Kenji Crosland
No probs Kenji! It's because it's an instance method of `ActiveMerchant::Billing::CreditCard` not of your model. You can use a callback to update an attribute before saving, then it will be persistently available.
Steve Graham
Good to know. I'll be sure to do that if it's necessary.
Kenji Crosland