我需要生成类似于“ABC1”和“XYZ9”的标签序列——始终是三个字母后跟一个数字。我希望标签的两个部分都能逻辑递增,并且始终保持准确的格式和长度。
我开始于:
sequence(:code) { |n| "ABC#{n}" }
那很好,但是在第九个标签 (
ABC9
) 之后,它转到了 (ABC10
),违反了我的格式,并且只生成 10 个(或 9 个?)值。
使用字母序列和硬编码一位数字的快速修复使得
26^3 => 17,576
实例不会出现我的翻转问题,这 可能 没问题。但是,我真的希望数字也有一些变化。随机数字可能就足够了......但我想要所有可用值。
我考虑了一些有点笨拙的方法,从一两个序列构建字符串以获得始终与格式匹配的综合值,但它们看起来很笨拙。
FactoryBot 中是否有一种优雅的方法来构建一个排序字符串,其中包含固定宽度的字母段,后跟固定宽度的数字段,以生成所有可能的值?
事实证明,工厂的解决方案非常简单且优雅:
FactoryBot.define do
factory :vault do
sequence(:code, 'AAA1')
end
end
这会产生以下序列:
FactoryBot.build :vault
=> #<Vault code: "AAA1">
=> #<Vault code: "AAA2">
=> #<Vault code: "AAA3">
=> #<Vault code: "AAA4">
=> #<Vault code: "AAA5">
=> #<Vault code: "AAA6">
=> #<Vault code: "AAA7">
=> #<Vault code: "AAA8">
=> #<Vault code: "AAA9">
=> #<Vault code: "AAB0">
=> #<Vault code: "AAB1">
=> #<Vault code: "AAB2">
... four hours later ...
=> #<Vault code: "ZZY7">
=> #<Vault code: "ZZY8">
=> #<Vault code: "ZZY9">
=> #<Vault code: "ZZZ0">
=> #<Vault code: "ZZZ1">
=> #<Vault code: "ZZZ2">
=> #<Vault code: "ZZZ3">
=> #<Vault code: "ZZZ4">
=> #<Vault code: "ZZZ5">
=> #<Vault code: "ZZZ6">
=> #<Vault code: "ZZZ7">
=> #<Vault code: "ZZZ8">
=> #<Vault code: "ZZZ9">
=> #<Vault code: "AAAA0">
=> #<Vault code: "AAAA1">
对于我的需求,我不关心 175,760 个值之后的总展期。
还值得注意的是,您可以在任意位置开始每个片段。这也同样有效:
sequence(:code, 'ABC9')
FactoryBot.build :vault
=> #<Vault code: "ABC9">
=> #<Vault code: "ABD0">
=> #<Vault code: "ABD1">
只是红宝石;没有导轨或其他什么:
code = "AAA0"
20.times{ puts code.succ! }