Open In App

How to convert String to Hash in Ruby?

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Converting string to hash using JSON parsing

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

Syntax:

hash = JSON.parse(string)

Example: In this example, the JSON string json_string is parsed using JSON.parse, resulting in a hash containing the key-value pairs from the JSON data.

Ruby
require 'json'

# Define a JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Convert JSON string to a hash
hash = JSON.parse(json_string)
puts hash
# Output: {"name"=>"John", "age"=>30, "city"=>"New York"}

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

Converting string to hash using YAML parsing

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

Syntax:

hash = YAML.safe_load(string)

Example: In this example the YAML string is parsed using YAML.safe_load, resulting in a hash containing the key-value pairs from the YAML data

Ruby
require 'yaml'

# Define a YAML string
yaml_string = "---\nname: John\nage: 30\ncity: New York\n"

# Convert YAML string to a hash
hash = YAML.safe_load(yaml_string)
puts hash
# Output: {"name"=>"John", "age"=>30, "city"=>"New York"}

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

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"}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads