How to URL Encode a String in Ruby

Jai Mahto 2 Mins
How to URL Encode a String in Ruby

Introduction

URL encoding, also known as percent encoding, is a technique used to safely represent data in a URL by replacing reserved and special characters with their corresponding percent-encoded values. In Ruby, you can achieve URL encoding using the built-in URI module, which provides the encode method for this purpose.

URL Encoding in Ruby

Here's how you can URL encode a string in Ruby using the URI module:

require 'uri'

# Original string
original_string = "Hello, World! How are you?"

# URL encoding
encoded_string = URI.encode(original_string)

puts "Original String: #{original_string}"
puts "Encoded String: #{encoded_string}"

Explanation

  1. Import the URI module with require 'uri'. This module contains the encode method required for URL encoding.

  2. Define your original string that you want to URL encode.

  3. Use the URI.encode method to encode the original string. This method replaces reserved and special characters with their percent-encoded equivalents.

  4. Print the original and encoded strings for verification.

Example Output

Original String: Hello, World! How are you?
Encoded String: Hello,%20World!%20How%20are%20you%3F

In the output, you can see that spaces have been encoded as %20, and the question mark ? has been encoded as %3F, ensuring that the URL is correctly formatted and data integrity is maintained. This URL-encoded string can now be safely included in a URL for web requests and other purposes.