DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Hide Credit Card Numbers

05.16.2007
| 4290 views |
  • submit to reddit
        // hide all digits of a credit card number except the last 4. eg<br/>
// cc = "12345678901123456"
// hide_card_number(cc)
// [ "************3456" ]

  def hide_card_number(card_number)
    size = card_number.to_s.size - 1
    cc = "" 
    i = 0
    0.upto(size) do 
      if( i > size - 4 )
      else
        cc += "*" 
      end
      i += 1
    end
    cc = cc + card_number[size-3, size].to_s
    return cc 
  end
    

Comments

Snippets Manager replied on Wed, 2007/05/16 - 11:08pm

or even: def hide_card_number(card_number,len=4,char='*') card_number.gsub(/^(.*)(.{#{len}})$/){char*$1.size + $2} end Okay, it's kind of similar to the previous one.

Snippets Manager replied on Mon, 2012/05/07 - 2:39pm

or: def hide_card_number(card_number) card_number.sub((part = card_number[0..-5]), '*' * part.length) end