String interpolation just evaluates the expression in #{ }
and calls to_s
on the return value and concatenates the prefix, the string returned and the postfix together to form a new string.
You code calls each
, which will return the original hash, so you see the to_s
return value of the hash is in the output. And the block attached to each is evaluated before the HEREDOC parameter is passed to puts <<COLORS
, so the output of the puts "#{...}"
in the block appears before the desired output.
You need to return the required part of the string. So, you have to do some transform of the original hash and then join the parts together with "\n"
to form the "colors" part of the output you need.
puts <<COLORS
--------------------------------------------------------------------------------
The colors of the rainbow:
#{ colors.map { |key, value| "#{key} (#{value})" }.join("\n") }
--------------------------------------------------------------------------------
COLORS
I would store the transform and join result in a variable before puts
and refer to that variable using string interpolation. I think it would be better to keep it simple in #{ }
.