-4

好吧,我是 ruby​​ 新手,我有这个 ID 生成器,它根据 Time.now.to_f/time.time() 生成一个 ID,然后是一个 8 长度的 id,例如这是工作的 python 版本

def anonId(a,b):
        a = a.split('.')[0]
        if len(a) > 4: i = a[6:]
        else: i = a
        return "".join(str(int(x) + int(y))[-1] for x, y in zip(i, b[4:]))

正在做

anonId("1379697991.99",'26002859') 

会生成 '9740' 的 ID 在 ruby​​ 中我已经尝试过这样的事情,但我不太了解 ruby​​ 还不知道该怎么做,但这是我到目前为止所拥有的

def anonId(number,id)
    if String(number).length > 4 then number = String(number).split(".")[0][-4..-1] else number end 
    [number,id[4..-1]].zip.each do |x,y|
       #this is where I get stuck at, I'm not sure if the above is correct

    end
end

所以基本上,我需要知道如何将 python 代码转换为 ruby

4

1 回答 1

3
  • 在 Ruby 中,你不能只迭代一个字符串——你必须指定如何(行、字节、代码点或字符)。
  • zip是 Array 上的一个方法,使用 like an_array.zip(other_array)
  • 如果你想迭代一个数组(或任何可枚举的),对每个元素做一些事情并将结果存储在一个数组中,使用map

这将导致number.chars.zip(id[4..-1].chars).map do |x,y|

注意 x 和 y 是字符串。x.to_i使用等将它们转换为整数。

于 2013-09-20T18:37:38.617 回答