2013-08-21 109 views
2
a = 'some string' 
b = URI.encode(a) # returns 'some%20string' 
c = URI.encode(b) # returns 'some%2520string' 

有紅寶石的方式通過,我可以解碼「C」這讓我對「一個」字符串無需解碼兩次。我的觀點是我有一些編碼了兩次的字符串,還有一些編碼了一次的字符串。我想要一個自動解碼爲正常字符串的方法來自動識別解碼的時間數。自動URI解碼需要

+0

你可以試試'URI.escape'和'URI.unescape' http://www.ruby-doc.org/stdlib-1.9.3/libdoc/uri/rdoc/URI/ Escape.html –

+0

URI.unescape只能使用一次。我想盡可能多地縮短它的編碼時間。 – shankardevy

+1

您無法自動確定。 – Stefan

回答

9

我想實現這一目標的唯一方法是繼續解碼,直到它停止進行更改。我對這種東西facvourite是do while循環:

decoded = encoded 
begin 
    decoded = URI.decode(decoded) 
end while(decoded != URI.decode(decoded) ) 

恕我直言,你正在尋找不存在。

********編輯*************

的另一個重複問題回答這個計算器上也表明了同樣的 How to find out if string has already been URL encoded?

2

我找不到文檔自動檢測,但它可能與一個額外的#decode調用實現這個方式如下:

def decode_uri(uri) 
    current_uri, uri = uri, URI.decode(uri) until uri == current_uri 
    uri 
end 

它將調用#decodeuri,直到它停止做任何更改。

0

這工作對我來說:

def decode_uri(encoded) 
    decoded = encoded 
    begin 
    decoded = URI.decode(decoded) 
    end while(decoded != URI.decode(decoded)) 
    return decoded 
end