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.
# 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
Contact Us