Last active
August 29, 2015 14:24
-
-
Save da4nik/c4ddf3de6804137043c2 to your computer and use it in GitHub Desktop.
Наложение маски на строку произвольной длины
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!ruby | |
module Masked | |
PLACEHOLDER = '@' | |
SPLITTERS = '-' | |
def self.render(mask, string) | |
str = string.chars | |
result = mask.chars.map do |c| | |
case | |
when str.size == 0 && (c == PLACEHOLDER) then nil | |
when c == PLACEHOLDER then str.slice!(0) | |
else c | |
end | |
end | |
result.push(str).join.gsub(/([#{ SPLITTERS }])+$/, '') | |
end | |
end | |
puts Masked.render('@@@', '5432') == '5432' | |
puts Masked.render('@-@@', '5432') == '5-432' | |
puts Masked.render('@-@@', '@432') == '@-432' | |
puts Masked.render('РОС@@-@@-@@@', '5432') == 'РОС54-32' | |
puts Masked.render('РОС@@-@@-@@@', '42') == 'РОС42' | |
puts Masked.render('@-@@-TAIL', '5432') == '5-43-TAIL2' | |
puts Masked.render('@-@@-@@@@@@@@@-TAIL', '5432') == '5-43-2-TAIL' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
➜ masked_test rvm:(2.1.5@rails) ruby ./masked.rb | |
true | |
true | |
true | |
true | |
true | |
true | |
true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment