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


can put conditional statement inside here-doc?

ie:

sky = 1 str = <<eof sky #{if sky == 1 blue else green end} eof 

thanks

yes, can. (did try it?) heredocs declared did act double-quoted string. if happened want reverse, single-quote heredoc indicator so:

str = <<eof   #{ "this interpolated ruby code" } eof  str = <<'eof'   #{ literal text } eof 

the "green" , "blue" in example wrong, unless have methods or local variables names. wanted either:

str = <<eof   sky #{if sky==1 'blue' else 'green' end} eof 

...or terser version:

str = <<eof   sky #{sky==1 ? :blue : :green} end 

as string interpolation, result of each expression has #to_s called on it. string representation of symbol same text, using symbols in interpolation saves 1 character when typing. use like:

cats = 13 str = "i have #{cats} cat#{:s if cats!=1}" 

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -