Custom String Parsing to Hash

In this method we implemented custom parsing logic to convert the string into a hash.

Syntax:

hash = Hash[string.split(‘&’).map { |pair| pair.split(‘=’) }]

Example: In this example we split the string into key-value pairs using delimiters such as ‘&’ and ‘=’ and then converting them into a hash.

Ruby
# Define a custom string format
string = "name=John&age=30&city=New York"

# Convert custom string to a hash
hash = Hash[string.split('&').map { |pair| pair.split('=') }]
puts hash
# Output: {"name"=>"John", "age"=>"30", "city"=>"New York"}

Output
{"name"=>"John", "age"=>"30", "city"=>"New York"}


How to convert String to Hash in Ruby?

In this article, we will discuss how to convert string to hash in ruby. We can convert a string to a hash through different methods ranging from parsing JSON and parsing YAML to custom string parsing.

Table of Content

  • Converting string to hash using JSON parsing
  • Converting string to hash using YAML parsing
  • Custom String Parsing to Hash

Similar Reads

Converting string to hash using JSON parsing

The JSON.parse method parses a JSON-formatted string and returns a hash representing the parsed data....

Converting string to hash using YAML parsing

The YAML.safe_load method is used to parse a YAML-formatted string into a hash....

Custom String Parsing to Hash

In this method we implemented custom parsing logic to convert the string into a hash....