开发者

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 prop开发者_如何学Cer 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


Here's a regex approach:

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

Here's an approach using string indexing:

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


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


You could use Ruby's gsub method and a regular expression to hide some of the numbers in the account number string:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜