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