IAmAkittycatAMA IAmAkittycatAMA - 5 months ago 10
Ruby Question

Why doesn't this variable display on page in Sinatra

Trying to show the

@total
variable but it always says
0
.

What's the correct way to get it to display on the page?

Currently i am doing...

main.rb

require 'sinatra'

get '/' do

@array = [1, 7, 3, 0]
@index = params[:index].to_i
@total = 1

def get_products_of_all_ints_except_at_index()
@array.delete_at(@index)
@array.each do |i|
@total *= i
end
end
get_products_of_all_ints_except_at_index()
erb :home
end


home.erb

<form action="/">

<input type="number" name="index" placeholder="index">

<button>Calculate</button>

</form>

<%= @total %>

Answer

In your @array, the last element is 0. Because you are iterating over it and multiplying the total with each element, total is 0 too.

Comments