2011-12-25 85 views
0

我是ruby和正则表达式的新手,我用PHP编写了这个函数,我需要将它重写为Ruby。如何将这个PHP函数重写为ruby?

function date_number_id($id_number) { 
    if (preg_match('~^([0-9]{2})([0-9]{2})([0-9]{2})/([0-9]{3,4})$~', $id_number, $match)) { 
     return (strlen($match[4]) < 4 || $match[1] >= 54 ? "19" : "20") . "$match[1]-" . sprintf("%02d", $match[2] % 50) . "-$match[3]"; 
    } 
    else 
    { 
     return false; 
    } 
} 

请问您能帮我吗?

非常感谢!

编辑:这是一个从身份证号码打印生日的功能。输入是例如:890807/5089

+0

它总是有助于提供一些输入/输出的人谁不进入PHP,但仍愿意帮助。 – 2011-12-25 11:34:26

+0

我更新了我的问题。 – user984621 2011-12-25 11:40:44

+0

嗯 - 这个例子不匹配 - 你需要在你的正则表达式中的前6个字符之后的斜线... – Amadan 2011-12-25 11:44:35

回答

1

除非我错过了一些东西......

def date_number_id(id_number) 
    match = /^([0-9]{2})([0-9]{2})([0-9]{2})\/([0-9]{3,4})$/.match(id_number) 
    if match 
    return "#{match[4].to_i < 4 || match[1].to_i >= 54 ? '19' : '20'}#{match[1]}-#{sprintf("%02d", match[2].to_i % 50)}-#{match[3]}" 
    else 
    return false 
    end 
end 

我觉得映射PHP是显而易见的,但如果有什么你不理解为什么是这样,问。