"Tex" has one more "x" than you think

So, you ask, "how many x's are there in Tex?" Funny you asked. We used to play a game in college, someone would ask that, and I would say "one more than you think."
Fun game. Let's try to code that.

How many x's do you think there are?

Whoa! How does that work? I'll tell you. No matter how many x's you put, Ruby will say one more.

Ruby code

  def index
    @number = params[:a_number]
    if @number  # make sure there is a number before we do all this work
		if @number =~ /^-?\d+\.?[\d+]?$/   # check for valid number
			if @number.to_i < 0            # check for negative
			  @texxx = "Tex has to have at least one x. Sorry."
			elsif @number.to_i > 999999     # check for too big
			  @texxx = "Ok, that number was too big. You got me!"
			else                            # respond to number
			  @texxx = "Tex" + "x" * @number.to_i +
			  " has one more x than you think!"
		else                                   # respond to text
			@texxx = "Tex" + @number + " has one more x than you think!"

This is as simple as code gets. We call this if/elsif/else/end. Ruby eats structures like this for breakfast, lunch and dinner. No problem.

if [condition] # if this is true

  # do something 

elsif [condition] # or if this is true

  # do something different

else # otherwise

  # do something else


This is great structure. See how well it reads? Clear, right? We do one thing between "if" and "end," and the possibilities are almost infinite.

My code has "ifs" nested inside each other, so the inner "ifs" are only checked if the first "if" is true. I check if you said anything, and only then do I respond. I see if you gave me a number, and only then do I check that it's in the range I'm looking for. (Ruby will get angry and bark at me if I ask it if something that's not a number is negative. She thinks it's a stupid question. I can't really disagree.) And I have a special place to respond to text in the "else." Else is like a catchall.

Rails code

That's a very interesting system, you say, but how does Ruby get into the web page? Excellent question. Remember Ruby's magic skateboard? It's Rails embedded in HTML.

<% form_tag :action => 'index' do %>
  <p>How many x's do you think there are?
  <%= text_field_tag 'a_number', @number %>
  <%= submit_tag 'Try' %></p>
<% end %>
<%= @texxx %>

Rails allows Ruby to collect your input and take it to the controller as parameter a_number. (The controller has all the Ruby code above. It sets the values of @number and @texxx so Rails can put them in your HTML.) Notice that this is Ruby code, but the code is encapsulated in <% %>. That structure tells the web server to use Rails.