Skip to content

Instantly share code, notes, and snippets.

@aldrinmartoq
Created March 20, 2019 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldrinmartoq/8f4d3b2cd46eb1ffb632ebcbdd2a53be to your computer and use it in GitHub Desktop.
Save aldrinmartoq/8f4d3b2cd46eb1ffb632ebcbdd2a53be to your computer and use it in GitHub Desktop.
class String # :nodoc:
def valid_rut?(out: {})
splitted = strip.split('-')
rut = splitted.first.delete('.').to_i
dv = rut.dv
valid = dv == splitted.last.upcase
if valid
out[:rut] = rut
out[:dv] = dv
out[:formatted] = rut.to_formatted_rut
end
valid
rescue StandardError
false
end
end
class Numeric # :nodoc:
def dv
reversed_digits = to_s.reverse.chars.map(&:to_i)
factors = (2..7).to_a.cycle
sum = reversed_digits.zip(factors).inject(0) { |s, (d, f)| s + d * f }
(-sum) % 11 == 10 ? 'K' : ((-sum) % 11).to_s
end
def to_rut
[to_s, dv].join('-')
end
def to_formatted_rut
[to_s.reverse.gsub(/...(?=.)/, '\&.').reverse, dv].join('-')
end
end
# Ejemplo de uso:
#
# 12345678.to_formatted_rut
# => "12.345.678-5"
#
# out = {}; "12.345.678-5".valid_rut?(out: out)
# => true
#
# out
# => {:rut=>12345678, :dv=>"5", :formatted=>"12.345.678-5"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment