Skip to content

Instantly share code, notes, and snippets.

@fukata
Last active Nov 24, 2020
Embed
What would you like to do?
番号フォーマット
#!/usr/bin/env ruby
require 'date'
def parse(format_str)
result = {
date: {},
num: false,
}
result[:date][:year] = true if format_str.include?('yyyy')
result[:date][:month] = true if format_str.include?('mm')
result[:date][:day] = true if format_str.include?('dd')
if m = format_str.match(/n+/)
result[:num] = true
end
result
end
def format(format_str, num: nil, date: nil)
result = format_str
if date
result.gsub!('yyyy', date.strftime('%Y'))
result.gsub!('mm', date.strftime('%m'))
result.gsub!('dd', date.strftime('%d'))
end
if m = result.match(/n+/)
len = m[0].size
result.gsub!(m[0], sprintf("%0#{len}d", num))
end
result
end
def main
format_str = 'yyyymmdd-nnnnn'
num = 100
date = Date.new(2020, 1, 1)
pp "format_str=#{format_str}, num=#{num}, date=#{date}"
pp parse(format_str)
pp format(format_str, num: num, date: date)
end
main
$ruby main.rb 
"format_str=yyyymmdd-nnnnn, num=100, date=2020-01-01"
{:date=>{:year=>true, :month=>true, :day=>true}, :num=>true}
"20200101-00100"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment