开发者

Ruby: Replace certain characters in an ascii range with their hex representations

I need to replace certain ascii characters like @ and & with their hex representations for a URL which would be 4开发者_StackOverflow社区0 and 26 respectively.

How can I do this in ruby? there are also some characters most notably '-' which does not need to be replaced.


require 'uri'
URI.escape str, /[@&]/

Obviously, you can widen the regex with more characters you want to escape. Or, if you want to do a whitelisting approach, you can do, say,

URI.escape str, /[^-\w]/


This is ruby, so there's a mandatory 20 different ways to do it. Here's mine:

>> a = 'one&two%three'                                                  
=> "one&two%three"                                                      
>> a.gsub(/[&%]/, '&' => '&'.ord, '%' => '%'.ord)                       
=> "one38two37three"  


I'm pretty sure Ruby has this functionality built in for URLs. However, if you want to define some more general translation facility you may use code like the following:

s = "h@llo world"
t = { " " => "%20", "@" => "%40" };
puts s.split(//).map { |c| t[c] || c }.join

Which would output

h%40llo%20world

In the above code, t is a hash defining the mapping from specific characters to their representation. The string is broken into characters and the hash is searched for each character's equivalent.


More generically and easily:

require 'uri'
URI.escape(your_string,Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜