url编码
URL Encode 关键字: ruby url encode
在Ruby中: URI.escape == URI.encode URI.unescape ==URI.decode
URI.escape (str):
采用ISO Latin字符集对指定的字符串进行编码。所有的空格符、标点符号、特殊字符以及其他非ASCII字符都将被转化成%xx格式的字符编码(xx等于该字符在字符集表里面的编码的16进制数字)。比如,空格符对应的编码是%20。unescape方法与此相反。
不会被此方法编码的字符有: /[-_.!~*'()a-zA-Z\d;\/?:;@&=+$,\[\]]/n
url =" http://HdhCmsTestgoogle.cn/search?q= 砂锅粥培训 &hl=zh-CN&start=0&sa=N"
>> URI.escape( url )
=>"http://HdhCmsTestgoogle.cn/search?q =%E7%A0%82%E9%94%85%E7%B2%A5%E5%9F%B9%E8%AE%AD &hl=zh-CN&start=0&sa=N"
>> URI.decode( url )
=> "http://HdhCmsTestgoogle.cn/search?q=砂锅粥培训&hl=zh-CN&start=0&sa=N"
两个Ruby小函数:URLDecode/URLEncode
作者:半瓶墨水 链接:http://HdhCmsTest2maomao测试数据/blog/2-ruby-cookies-en-de-code/
在解码、编码URL时常用到的URLDecode和URLEncode,用Ruby写了一下,应该可以应付中英文的情况了:
def URLDecode ( str )
str . gsub ! ( / %[a-fA-F0-9]{2} / ) { | x | x = x [ 1..2 ] . hex . chr }
end
def URLEncode ( str )
str . gsub ! ( / [^ \w $& \- +., \/ :;=?@] / ) { | x | x = format ( " %%%x " , x [ 0 ]) }
end
tmd,ruby太不是东西,没有Char这个类型,一个字符转为一个整型值很容易,一个整形转回一个字符的方法我查了n久才发现原来可以用Integer:chr函数解决。
Update:
好吧,我承认,我是一个Ruby土人:CGI::escape, CGI::inescape, CGI::escapeHTML, CGI::inescapeHTML,
参见: http://HdhCmsTestruby-doc.org/core/classes/CGI.html