2.9 Control Flow with Embedded Ruby

With the power of Ruby, we can actually compute who won or lost our Rock, Paper, Scissors match on the page before rendering the HTML to the user. Add the following if-else embedded Ruby code to our view template:

<!-- app/views/game_templates/user_rock.html.erb -->

<h2>We played rock!</h2>

<% comp_move = ["rock", "paper", "scissors"].sample %>

<h2>
  They played <%= comp_move %>!
</h2>

<% if comp_move == "rock" %>
  <h2>We tied!</h2>
<% elsif comp_move == "paper" %>
  <h2>We lost!</h2>
<% elsif comp_move == "paper" %>
  <h2>We won!</h2>
<% end %>

{: mark_lines=“11-17”}

Do you understand this added code? Read it carefully and try to understand the logic before you keep reading.

We used hidden <% %> embedded Ruby tags in our control flow on each line we wanted to hide from the user. Only the result of this control flow <h2>We tied!</h2>, <h2>We lost!</h2>, or <h2>We won!</h2> will be rendered, depending on the randomly sampled comp_move variable. Refresh /rock a few times to see.

If you haven’t, now would be a good time to run rails grade at the GitPod terminal to check your progress. And remember to Always Be Committing (ABC), by making a /git commit. We have a lot done, but we still have a lot to do.

2.9.1 Completed Code

<!-- app/views/game_templates/user_rock.html.erb -->

<h2>We played rock!</h2>

<% comp_move = ["rock", "paper", "scissors"].sample %>

<h2>
  They played <%= comp_move %>!
</h2>

<% if comp_move == "rock" %>
  <h2>We tied!</h2>
<% elsif comp_move == "paper" %>
  <h2>We lost!</h2>
<% elsif comp_move == "paper" %>
  <h2>We won!</h2>
<% end %>