The code below defines a Sinatra route and includes a method initially written to print a shape at the command line.
The method was modified so the return value was displayed in the browser instead.
The comments make it a bit harder to read, but hopefully the intent remains relatively clear.
Also, if you're not familiar with until loops, they basically run until the initial condition you set, is met.
In this case, until the variable counter is equal to height + 1 (in the example below,5), do the following stuff.
require'sinatra'defshow_paramspparamsendget("/home")doerb(:home)endget("/pyramid")do# Use a form to make a GET request to "/pyramid"# debugging/learning method, shows contents of params hashshow_params()defprint_horizontal_pyramid(height)counter=height/height# print counter to terminalpcounter# print a new line in terminalputs"\n"# new var set to empty arraypyramid_array=# until loop, until counter is equal to height + 1 (e.g. 5), do the next lineuntilcounter==height+1pyramid_array.push("<h3>"+" "*(height-counter)+"*"*((counter)+(counter))+"</h3>")# check the terminal to see what the array looks like each time the loop happens.ppyramid_array# add one to the countercounter+=1# print out each iteration of the counterpcounterend# return the result of the final iterationpyramid_arrayend# takes in the param height, string form, and converts to an integerheight=params[:height].to_i# runs the method we defined aboveprint_horizontal_pyramid(height)end
Here's what the terminal output looks like.
Here is the associated form that can be added to the home.erb page.
I used forms for the input instead of having to manually add the parameters via the address bar.
<formmethod="GET"action="/pyramid"><inputtype="text"name="height"placeholder="Number of stars"><inputtype="submit"value="submit"></form>
Parameters are passed from the client (browser) to the server as a hash, a key | value pair.
Hashes passed between the client and server often look like this.
In the form above, the name field will set the key, "height" in the param hash. The value corresponds the number we choose to enter when filling out the form, in this case, "4".
You can return any object that would either be a valid Rack response, Rack body object or HTTP status code:
* An Array with three elements: [status (Fixnum), headers (Hash), response body (responds to #each)]
* An Array with two elements: [status (Fixnum), response body (responds to #each)]
* An object that responds to #each and passes nothing but strings to the given block
* A Fixnum representing the status code
Since the object we're returning, an array, responds to .each, it is passed and rendered.
This post assumes an application directory structure that resembles:
If you attempt to mirror or use this code and have a problem, reach out to [email protected]