Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

heredoc

ruby

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

like image 504
Matt Avatar asked Dec 03 '10 05:12

Matt


People also ask

How can we apply conditional statements?

Example: We have a conditional statement If it is raining, we will not play. Let, A: It is raining and B: we will not play. Then; If A is true, that is, it is raining and B is false, that is, we played, then the statement A implies B is false.

What are the two commands that used for conditional statement?

To better understand deductive reasoning, we must first learn about conditional statements. A conditional statement has two parts: hypothesis (if) and conclusion (then). In fact, conditional statements are nothing more than “If-Then” statements!

What is the use of Here document in php?

Heredoc is one of the ways to store or print a block of text in PHP. The data stored in the heredoc variable is more readable and error-free than other variables for using indentation and newline.


1 Answers

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}"
like image 129
Phrogz Avatar answered Sep 29 '22 20:09

Phrogz