Question

Can you put a conditional statement inside a here-doc?

IE:

sky = 1
str = <<EOF
The sky is #{if sky == 1 then blue else green end}
EOF

Thanks

Was it helpful?

Solution

Yes, you can. (Did you try it?) HEREDOCs declared as you did act like a double-quoted string. If you happened to want the reverse, you would single-quote your HEREDOC indicator like so:

str = <<EOF
  #{ "this is interpolated Ruby code" }
EOF

str = <<'EOF'
  #{ This is literal text }
EOF

The "green" and "blue" in your example are wrong, unless you have methods or local variables with those names. You probably wanted either:

str = <<EOF
  The sky is #{if sky==1 then 'blue' else 'green' end}
EOF

...or the terser version:

str = <<EOF
  The sky is #{sky==1 ? :blue : :green}
end

As with all string interpolation, the result of each expression has #to_s called on it. As the string representation of a symbol is the same text, using symbols in interpolation like that saves one character when typing. I use it most often like:

cats = 13
str = "I have #{cats} cat#{:s if cats!=1}"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top