I'm trying to design a simple Ruby calculator and I'm getting an error -


so i've been messing around ruby first time after finishing codecademy course "object oriented programming, part i" , decided start making calculator. reason though, error:

calc.rb:13:in `addition': undefined local variable or method `user_input' main:object (nameerror)   calc.rb:21:in `<main>' 

i'm confused why doesn't see "user_input" array. out of scope of method? did initialize wrong?

here's code can see yourself, it's nothing sophisticated , it's not finished. i'm trying test addition right now.

#!/usr/bin/env ruby  user_input = array.new  puts "would [a]dd, [s]ubtract, [m]ultiply, or [d]ivide? "  type_of_math = gets.chomp  def addition   operator = :+   puts "please enter numbers want add (enter \"=\" stop adding numbers): "   until gets.chomp == "="     user_input << gets.chomp.to_i   end   sum = user_input.inject(operator)   return sum end  case type_of_math when "a"   addition when "s"   puts "test subtraction" when "m"   puts "test multiplication" when "d"   puts "test division" else   puts "wrong" end 

consider untested variation on code. it's more idiomatic:

def addition   user_input = []   puts 'please enter numbers want add (enter "=" stop adding numbers): '   loop     input = gets.chomp     break if input == '='     user_input << input   end   user_input.map(&:to_i).inject(:+) end 

notice puts user_input method. uses normal [] direct assignment of empty array initialize it. rather chomp.to_i each value it's entered waits until after loop exits.

instead of while loops, consider using loop do. tend more seen when scanning code.

also notice there's no return @ end of method. ruby automatically returns last value seen.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -