Skip to content

Instantly share code, notes, and snippets.

@da4nik
Last active August 29, 2015 14:24
Show Gist options
  • Save da4nik/c4ddf3de6804137043c2 to your computer and use it in GitHub Desktop.
Save da4nik/c4ddf3de6804137043c2 to your computer and use it in GitHub Desktop.
Наложение маски на строку произвольной длины
#!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'
➜ 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