String operation in ruby ​​for credit card number

Work on the rails project, where an order confirmation line was marked with a credit card number with all but the last four digits. What is the correct way to do string replacements?

What operation to get this

credit_card_number = "1111111111111111"

to that?

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

Thanks,

Kenji

+3
source share
3 answers

If you use ActiveMerchant, it ActiveMerchant::Billing::CreditCardhas an instance method called display_numberthat does this, for example. XXXX-XXXX-XXXX-4338

If you do 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
+9
source

Here's a regex approach:

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

:

x = '*' * (x.size - 4) + x[-4, 4]
+15

Ruby gsub , :

hidenumber = "123-123-1234"
hidenumber.gsub(/(\d{3}-\d{3})/,"xxx-xxx")
+2
source

Source: https://habr.com/ru/post/1725678/


All Articles