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
"#{params[:int1].to_i + params[:int2].to_i}"
you need to pass it in url
http://yourdomain/add/2/3 #=> this will display 5 :int1 => 2, :int2 => 3
for embedding/interpolating variables use double quotes with puts
puts "#{params[:int1]} + #{params[:int2]}"
Here is something that should work:
require 'sinatra'
get '/add/:int1/:int2' do
sum = params[:int1].to_i + params[:int2].to_i
"#{sum}"
end
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 into String
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
, using to_i
they will always be String
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.
It's more readable with block parameters:
get "/add/:int1/:int2" do |a, b|
"#{a.to_i + b.to_i}"
end
You can even use Regular Expressions to ensure integers:
get %r{/add/(\d+)/(\d+)} do |a, b|
"#{a.to_i + b.to_i}"
end