How can I display in my web page the result of int1 + int2
? And can I know if it's an integer or a string? Here is my code:
require 'sinatra'
get '/add/:int1/:int2' do
puts #{params[:int1]} + #{params[:int2]}
end
How can I display in my web page the result of int1 + int2
? And can I know if it's an integer or a string? Here is my code:
require 'sinatra'
get '/add/:int1/:int2' do
puts #{params[:int1]} + #{params[:int2]}
end
you need to pass it in url
for embedding/interpolating variables use double quotes with puts
It's more readable with block parameters:
You can even use Regular Expressions to ensure integers:
Here is something that should work:
I have changed the following:
Removed
puts
- it's fine for debug, but Sinatra uses the return value, not STDOUT (which frameworks based around CGI might use) to output via web server. I am assuming here you are viewing in a browser.Removed the
#{ variable }
syntax - this is for inserting calculations intoString
results, and is not needed here. If you were building up a more complex string, it could be the way to go.Converted the params to
Fixnum
, usingto_i
they will always beString
initially. Which conversion to apply, and how to validate you really have convertable numbers, well that's a bit more complicated, perhaps another question if it bothers you.Finally, returned number as a
String
, using string interpolation, because if you return just a number, Sinatra takes that for the HTTP status code.Note that the separation into calculation, and turning the result into a string, is not strictly necessary. I have done it here just to show how the two parts are in fact different things you need to do.