生成特殊的安全ID

时间:2016-09-19 14:47:44

标签: ruby-on-rails ruby

我必须以类似于ABC-4F-ABC-8D-ABC的格式生成唯一引用(其中:ABC是随机3字符串,4F,8D是随机十六进制数字)。 我是红宝石的新人,所以请原谅我,如果这是重复的(到目前为止没有发现类似的smth)。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您需要的一切都内置于Ruby中。

您可以创建一个字母数组,然后从中选择sample以形成字符串:

ALPHA = ('A'..'Z').to_a # might also want to add numbers or lower-case letters?
HEX = ('A'..'F').to_a + (0..9).to_a

def generate_string(alphabet, length)
  # pick random elements from the alphabet and concatenate 
  # until length is reached.
  # key method is `sample` which selects a random element from 
  # an array (the alphabet, in your case)
  # you can try it on irb like so:
  # [1, 2, 3].sample
end

然后你可以做类似的事情:

def generate_unique_reference
  "#{generate_string(ALPHA, 3)}-#{generate_string(HEX, 2)}-....."
end

我会留给你完成练习(听起来像是家庭作业,不是吗?)