How to read a YAML file in ruby
- User
How to read a YAML file in ruby
Assistant
To read a YAML file in Ruby, you can use the
YAMLmodule. Here's an example code snippet:rubyrequire 'yaml' # Read the YAML file data = YAML.load_file("file.yaml") # Print the data puts data["key"]In this example,
"file.yaml"is the path to the YAML file. TheYAML.load_filemethod reads the YAML file and returns the data stored in it. The data is then printed to the console.You can also use the
loadmethod with a block to load the YAML file more efficiently. Here's an example:rubyrequire 'yaml' # Read the YAML file YAML.load_file("file.yaml", :block => { |data, key| puts data[key] }) # Print the data puts data["key"]In this example, the
:blockoption is used with theload_filemethod to pass a block of code to be executed when the YAML file is loaded. The block takes two arguments,dataandkey, which are passed to theputsstatement to print the data.I hope this helps! Let me know if you have any questions.