Newbie Rubyist wants to get the concept of YAML

I am reading ‘Learning to Code’ by Chris P…

One section talks about Yaml. In Chris’s code, he always puts a test at
the end (e.g. ‘puts(read_array == test_array)’ ) I am wondering what it
does! Thanks!!

The attached screenshot is the complete script he used as an example.

THANKS!!

So, this example doesn’t have much to do about YAML, except that YAML is
a way to serialize an object, much like Marshal.

What the example demonstrates is that you can serialize and deserialize
an Array to/from a file.

try this from your command line

ruby -ryaml -e ‘puts YAML::dump %w[a b c]’
and then
ruby -ryaml -e ‘yaml = YAML::dump( %w[a b c] ); p YAML::load(yaml)’

Benjamin F. wrote in post #1166359:

So, this example doesn’t have much to do about YAML, except that YAML is
a way to serialize an object, much like Marshal.

What the example demonstrates is that you can serialize and deserialize
an Array to/from a file.

try this from your command line

ruby -ryaml -e ‘puts YAML::dump %w[a b c]’
and then
ruby -ryaml -e ‘yaml = YAML::dump( %w[a b c] ); p YAML::load(yaml)’

Thank you for your response Benjamin!

But I am sorry if I sound dumb…I have never come across anything like
the two lines above…what exactly do they do?? Thanks in advance!!

It a ruby program that you can type in and run entirely from the command
line. No need to save it in a file and run it from a file.

ruby --help

-rlibrary require the library before executing your script

-ryaml loads the yaml library. It’s the equivalent of the require ‘yaml’
line in the Pine example.

-e ‘command’ one line of script. Several -e’s allowed.

The program code then follows in single quotes following the -e.

‘puts YAML::dump %w[a b c]’

For that line of code try reading it from right to left.

%w[a b c] create an array containing three characters. It’s a shortcut
way of typing [‘a’, ‘b’, ‘c’]. Open up irb and try it:

C:\Users\Scott>irb --simple-prompt

%w[a b c]
=> [“a”, “b”, “c”]

exit

dump is a method in the yaml library. Your passing in the array to that
method. YAML::dump(%w[a b c])

puts just sends the output to the console rather than to a file. But
what you see is the contents of the array in the YAML format. You can
look up more about YAML online.

Here’s the whole thing in irb:

C:\Users\Scott>irb --simple-prompt

require ‘yaml’
=> true

puts YAML::dump %w[a b c]


  • a
  • b
  • c
    => nil

exit