How to add two parameters from the url

2019-09-02 18:37发布

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

标签: ruby sinatra
4条回答
▲ chillily
2楼-- · 2019-09-02 19:11

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]}"
查看更多
老娘就宠你
3楼-- · 2019-09-02 19:17

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
查看更多
你好瞎i
4楼-- · 2019-09-02 19:29

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.

查看更多
我想做一个坏孩纸
5楼-- · 2019-09-02 19:33
"#{params[:int1].to_i + params[:int2].to_i}"
查看更多
登录 后发表回答