DEV Community

Aldo Portillo
Aldo Portillo

Posted on • Updated on

TIL: Dynamic Paths

Introduction

I was working on a simple rock, paper, scissors app in Ruby. The first exercise was to create it and to create an individual route for each user option.

get("/rock"){...}
get("/paper"){...}
get("/scissors"){...}
Enter fullscreen mode Exit fullscreen mode

I knew there had to be a simpler way to do this without declaring that many static routes considering my views file was a singular file.

I learned that to declare a dynamic path segment all that needs to happen is to add a semi-colon /:path in front of whatever part of the path you'd like to make dynamic, and it will accept any input to store in a params hash.

I was then able to declare a dynamic route to accept any input to be extracted.

get(/:user_input){
@user_input = params.fetch("user_input").to_s
@computer_input = #Logic for random RPS selection

##conditionals
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)