How to add two parameters from the url

有些话、适合烂在心里 提交于 2019-12-11 22:17:23

问题


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

回答1:


"#{params[:int1].to_i + params[:int2].to_i}"



回答2:


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:


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.




回答4:


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


来源:https://stackoverflow.com/questions/18656505/how-to-add-two-parameters-from-the-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!