nicholasdorta
nicholasdorta

Reputation: 1

How can i make a calculator in ruby

I was trying to make a calculator in ruby a very simple one because i am new to the language and i barely know any code but when i run this it is asking me for the variable then does Enter First Value instead of asking first. How can i fix it.

while true do

x = gets.chomp
  puts "Enter First Value:" , x 
  
op = gets.chomp
  puts "Enter Operator" , op

y = gets.chomp
  puts "Third value" , y
 
z = eval( x + op + y)
  puts "=" , z
  
end

Upvotes: 0

Views: 247

Answers (2)

Kjartan
Kjartan

Reputation: 21

There are situations which justify the use of eval, but those are extremely rare - avoid it whenever possible.

For your calculator, you should interpret and convert your input instead. Your values should be converted from strings to numbers, and for your operator you should call the corresponding method on your first value.

With a bit of styling and minimal error handling it could look something like this:

def convertValue x
  case x
  when String
    x= x.scan(/^\d+.?\d*$/)[0]
    x&&x.to_f
  else
    (x%1).zero? ? x.to_i : x
  end
end

loop do
  print "\nEnter First Value:     "
  x= convertValue gets  
  unless x
    puts "Having trouble understanding your value :-("
    next
  end
  
  print "Enter Operator:        " 
  op = gets.chomp.to_sym
  unless x.respond_to?(op, :include_private)
    puts "Having trouble understanding your operator :-("
    next
  end

  print "Enter Second value:    "
  y= convertValue gets 
  unless y
    puts "Having trouble understanding your value :-("
    next
  end 
  z= x.send op, y
  puts  "                     = #{convertValue z}"
end

With the x.to_f in line 5, your values become floats. By calling to_sym on your operator string, it becomes a symbol - which you can then use to call the corresponding method in z= x.send op, y(which you can read something like call the method named op on x with the parameter y and assign the result to z)

Upvotes: 0

castelo
castelo

Reputation: 11

Your code should print the puts message first and then obtain the user input.

while true do

  puts "Enter First Value:"
  x = gets.chomp

  puts "Enter Operator"
  op = gets.chomp

  puts "Third value"
  y = gets.chomp

  z = eval( x + op + y)
  puts "=" , z
end

Upvotes: 1

Related Questions