tags:

views:

109

answers:

6

For the following code, why does only "World" gets printed

get '/' do
 "Hello"
 "World"
end
+4  A: 

Correct me if I'm wrong, but I do believe in plain ruby, the last line evaluated is what gets returned.

Damien Wilson
+10  A: 

This has nothing to do with sinatra itself. It just uses the return value of the block and in ruby the return value is the last evaluated expression, which in your case is "World". This might work for you:

get '/' do
  r = "Hello"
  r += "World"
end

In this case you add as many string values to r as you want and the last expression would return the complete string "HelloWorld".

Tomas Markauskas
Still, using + generates a new string object every time. Try using << instead.
Mereghost
+1  A: 

You could use a line break char to separate lines..

get '/' do
"Hello\nWorld"
end
rubyphunk
+2  A: 

Tomas correctly answered your question, but one way to do what I think you're meaning to do (output multiple lines), you could use:

get '/' do
  output =<<EOS
Hello
World
EOS
  output
end
Pete Hodgson
+1  A: 

Don't confuse your controller with your view.

What you're probably looking for is this:

get '/' do
  haml :hello_world
end

And then in views/hello_world.haml:

Hello
World
Matt Zukowski
A: 

I agree with Matt.

If you want you can use that method with one file too.

 get '/' do
   erb :hello_world
 end

_END_

@@hello_world
hello
world

I just use puts inside my controller to get some debug printed to STDOUT.

Cheers, Francisco

include