Skip to content

Instantly share code, notes, and snippets.

@siadat
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save siadat/bc405c3a4ed1d07e4726 to your computer and use it in GitHub Desktop.

Select an option

Save siadat/bc405c3a4ed1d07e4726 to your computer and use it in GitHub Desktop.
Clean mobile number

Example usage

ruby clean.rb 09121001234 9121001234 989121001234 00989121001234 09001001234
#!/usr/bin/env ruby
# Example usage:
#
# ruby clean.rb 9121001234
#
module Mobile
PREFIXES = {
"901"=>"mtn",
"902"=>"mtn",
"930"=>"mtn",
"933"=>"mtn",
"934"=>"mtn",
"935"=>"mtn",
"936"=>"mtn",
"937"=>"mtn",
"938"=>"mtn",
"939"=>"mtn",
"932"=>"taliya",
"910"=>"mci",
"911"=>"mci",
"912"=>"mci",
"913"=>"mci",
"914"=>"mci",
"915"=>"mci",
"916"=>"mci",
"917"=>"mci",
"918"=>"mci",
"919"=>"mci",
"940"=>"mci",
"920"=>"rightel",
"921"=>"rightel",
}.freeze
RE_MOBILE = /^0(9\d{2})(\d{7})$/
RE_COUNTRY = /^(\+|00)?98/
# Try to clean the number
def self.clean(number)
return number if valid?(number)
number = number.sub(RE_COUNTRY, '').strip
number = "0#{number}" if number.chr != '0'
fail "invalid_mobile_number_format" unless valid?(number)
number
end
# Check if number is valid
def self.valid?(number)
RE_MOBILE =~ number
PREFIXES.key?($1)
end
end
if ARGV.none?
puts "Usage: ruby #{__FILE__} [<mobile>...]"
exit 1
end
ARGV.each do |mobile|
begin
puts Mobile.clean(mobile)
rescue Exception => e
puts "#{e}: #{mobile}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment