New to Ruby, tried to build the simplest calculator, why is it not working? -


class calculator   def firsti     puts "please type first number: "   end    def initialize(x)     @x = gets.chomp   end    def opi     puts "please type operation: "   end    def initialize(y)     @y = gets.chomp   end    def secondi     puts "please type second number: "   end    def initialize(z)     @z = gets.chomp   end    if @y == '+'     puts @x+@z   elsif @y == '-'     puts @x-@z   elsif @y == '*'     puts @x*@z   elsif @y == '/'     puts @x/@z   else     puts "something went wrong. please try again."   end end 

tried spaces, or without ()-s, no error messages, i'm jut noob. appreciated. tried simple variables without class, no result though when write simple

x = 2 y = + z = 3 if y == '+'   puts x+z end 

and worked. can't seem understand problem.

here "working version" of code, have tried make minimal changes design:

class calculator     def initialize      puts "please type first number: "      @x = gets.chomp.to_i      puts "please type operation: "      @y = gets.chomp      puts "please type second number: "      @z = gets.chomp.to_i    end      def result      if @y == '+'        @x+@z      elsif @y == '-'        @x-@z      elsif @y == '*'        @x*@z      elsif @y == '/'        @x/@z      else        "something went wrong. please try again."      end    end   end   calculator = calculator.new  puts "result is:"  puts calculator.result 

your code has several issues preventing working expect:

  • you have defined multiple initialize methods in single class. not possible; you're doing *re-*defining same method.
  • your code has no sense of flow control. seem under impression "the code run, top bottom". not how methods/classes work; first define methods/classes, , call them. can see in code, explicitly creating calculator object (calculator.new - constructs new instance, calling initialize method), , calling result method.
  • on similar note, performing conditional check on @y variable hasn't been defined @ point in code's execution! @y nil when if statement executes; therefore, logic falls through else statement.
  • a more subtle point, input gets command string. need call to_i convert integer; otherwise, you'll funny results like: "2" + "5" == "25"

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -