I want to make a four-functioning calculator. I tried to make methods that would store operations.
def mul
puts num1*num2
end
def div
puts num1/num2
end
def sub
puts num1-num2
end
def add
puts num1+num2
end
num1=gets.chomp.to_f
op=gets.chomp
num2=gets.chomp.to_f
puts "Multiplication=mul\n Addition=add\n Subtract=sub\n Division=div"
puts ("This is your answer"+num1+op+num2)
But I couldn't make the calculator.
I tried running the code, but it won't work. Can someone help?
Best Way to do so, is
def perform_operation(op, a, b)
op = { 'add' => '+', 'sub' => '-', 'mul' => '*', 'div' => '/' }[op]
a.send(op, b)
end
num1=gets.chomp.to_f
op=gets.chomp
num2=gets.chomp.to_f
puts "This is your answer", perform_operation(op, num1, num2)
If your op is +, -, * or / passed by input you can directly do it without method like below,
puts "This is your answer", num1.send(op, num2)
Once you defined the methods with parameters, for example:
def sub(x, y)
x - y
end
def add(x, y)
x + y
end
Once you gat the variables set by user input (I'm assigning by hard coding just to show):
op = "add".to_sym # or user input
num1 = 10 # or user input
num2 = 20 # or user input
You can use the case expression to select the result to show.
For example:
res = case op
when :add
add(num1, num2)
when :sub
sub(num1, num2)
end
So you can show the result as:
puts res
As mentioned, you can also call the method on the user input using send:
How to call methods dynamically based on their name?
Ruby difference between send and instance_eval?
Using heredoc and proc
def mul(num1, num2)
num1 * num2
end
def div(num1, num2)
num1 / num2
end
def sub(num1, num2)
num1 - num2
end
def add(num1, num2)
num1 + num2
end
puts 'First number'
num1 = gets.to_f
puts 'Second number'
num2 = gets.to_f
puts <<-OPERATORS
Multiplication = mul
Addition = add
Subtract = sub
Division = div
OPERATORS
op = method(gets.chomp).to_proc
puts "This is your answer: #{op.call(num1, num2)}"
How it works on the example of String#downcase:
downator = :downcase.to_proc
downator.call('WORD') #=> "word"
# It is equal to
'WORD'.downcase #=> "word"
It is because downator stores block proc { |arg| arg.downcase }
In practice, this property is often used for operations with arrays, for example:
['WORD', 'STRING'].map(&:downcase) #=> ["word", "string"]
# It is equal to
['WORD', 'STRING'].map { |arg| arg.downcase } #=> ["word", "string"]
You can't use local variables defined outside a method within that method. Instead, you have to pass it as an argument:
def mul(num1, num2)
puts num1 * num2
end
You also don't have to use the same variable names, use whatever makes sense in the context of the method:
def mul(a, b)
puts a * b
end
mul(2, 3)
# prints 6
Methods usually become more versatile if they do one thing. The above implementation multiplies a and b and then prints the result via puts. Let's move the printing outside the method:
def mul(a, b)
a * b
end
puts mul(2, 3)
# prints 6
We can now perform actual calculations:
x = mul(2, 3) #=> 6
y = mul(2, 5) #=> 10
puts mul(x, y)
# prints 60
This wouldn't have been possible with the variant which incorporated puts.
With user input and output: (using whole numbers for demonstration purposes)
print "first factor: "
num1 = gets.to_i
print "second factor: "
num2 = gets.to_i
puts "#{num1} * #{num2} = #{mul(num1, num2)}"
Note that #{...} is needed to interpolate other values.
Example session:
first factor: 2
second factor: 3
2 * 3 = 6
To have different output based on a given operator, you need a conditional, e.g. a case statement:
op = gets.chomp
case op
when 'mul'
puts mul(num1, num2)
when 'add'
puts add(num1, num2)
# ...
end
Hope this will get you started.
Related
I'm creating a new calculator in Ruby. However, I keep experiencing this problem: The "if" statement is not executed even though I typed "add" if I want to add numbers together. Same with the "elsif" statements. The "else" statement will be always executed.
Pardon my messy code. I’m getting started in Ruby
class CalculatorFunctions
def addNumbers(num1, num2)
#n1 = num1
#n2 = num2
#sum = #n1 + #n2
puts #sum
end
def subtractNumbers(num1, num2)
#n1 = num1
#n2 = num2
#difference = #n1 - #n2
puts #difference
end
def multiplyNumbers(num1, num2)
#n1 = num1
#n2 = num2
#product = #n1 * #n2
puts #product
end
def divideNumbers(num1, num2)
#n1 = num1
#n2 = num2
#quotient = #n1 / #n2
puts #quotient
end
end
calcFunctions = CalculatorFunctions.new
puts "Select a method:\nType 'add' for Addition\nType 'subtract' for Subtraction\nType 'multiply' for Multiplication\nType 'divide' for Division"
method = gets
puts "Enter the first number:"
num1 = gets.to_i
puts "Enter the second number:"
num2 = gets.to_i
if method == "add" or method == "Add"
calcFunctions.addNumbers(num1, num2)
elsif method == "subtract" or method == "Subtract"
calcFunctions.subtractNumbers(num1, num2)
elsif method == "multiply" or method == "Multiply"
calcFunctions.multiplyNumbers(num1, num2)
elsif method == "divide" or method == "Divide"
calcFunctions.divideNumbers(num1, num2)
else
puts "Invalid method"
end
Remove Newlines from Input
When you call method = gets, you also capture the newline when the user presses RETURN. You need to strip the newline from your input with String#chomp or String#strip.
method = gets.chomp
Alternatively, you could swap out the equality checks in your if-statements for String#start_with?. That would solve the problem too, but is a less idiomatic approach to what you're trying to do.
This is not an answer but an extended comment that cannot be easily expressed in one or more conventional comments. Accordingly, no upvotes please (downvotes OK).
Firstly, there is not reason to put your methods in a class because you will not be creating instances of the class. You could put the methods in a module, which you could then Module#include in classes as needed. As an example, look at Ruby's built-in Math module. They are all module methods, so they are invoked with the module name. For example,
Math.sqrt(25)
Next, notice that the four basic arithmetic methods are similar in that they all have two arguments and one operator. We therefore can simplify the code by writing a single method that applies to all.
module Calc
def self.compute(op, arg1, arg2)
arg1.public_send(op, arg2)
end
end
See #public_send.
Let's try it.
Calc.compute(:+, 2, 3) #=> 5
Calc.compute(:-, 2, 3) #=> -1
Calc.compute(:*, 2, 3) #=> 6
Calc.compute(:/, 7, 2) #=> 3
Calc.compute(:/, 7.0, 2) #=> 3.5
Note that we can alternatively pass the operator as a string rather than a symbol.
Calc.compute('+', 2, 3) #=> 5
Because we want separate methods for each operator we can write the module Calc as follows.
module Calc
def self.add(arg1, arg2)
compute(:+, arg1, arg2)
end
def self.subtract(arg1, arg2)
compute(:-, arg1, arg2)
end
def self.multiply(arg1, arg2)
compute(:*, arg1, arg2)
end
def self.divide(arg1, arg2)
raise ZeroDivisionError if arg2.zero?
compute(:/, arg1, arg2)
end
private
def self.compute(op, arg1, arg2)
arg1.public_send(op, arg2)
end
end
Calc.add(2, 3) #=> 5
Calc.subtract(2, 3) #=> -1
Calc.multiply(2, 3) #=> 6
Calc.divide(7, 2) #=> 3
Calc.divide(7.0, 2) #=> 3.5
Calc.divide(7.0, 0) #=> ZeroDivisionError
Curiously, had I not raised a divide-by-zero exception in Calc::divide when the second argument is zero, the following would result.
Calc.divide(7.0, 0) #=> Infinity
You can obtain the arguments as follows.
print "Enter the method, 'add', 'subtract', 'multiply' or 'divide': "
method = gets.strip.downcase
puts
print "Enter the first number: "
num1 = gets.to_i
puts
print "Enter the second number: "
num2 = gets.to_i
Then, if, say, method = 'add', num1 = 2 and num2 = 5.
Calc.public_send(method, num1, num2) #=> 7
Notice that I've not created any instance variables. Also, Ruby has a convention to use Snake case for naming variables and methods. You don't have to follow that, but 99%+ of Rubyists do.
simple calculator using switch statement in ruby
puts "Entre first number"
num1 = gets.chomp().to_f
puts "Entre operator"
op = gets.chomp()
puts "Entre second number"
num2 = gets.chomp().to_f
case op
when "+"
puts(num1 + num2)
when "-"
puts(num1 - num2)
when "*"
puts(num1 * num2)
when "/"
puts(num1/num2)
end
Trying to write a program interactively which can take inputs from command line as an expression or attributes like -
irb : 3+2
Should evaluate to => 5
Attribute
irb : abc = 1
=> 1
irb : jkl(or def) = 1
=> 1
irb : abc + def
=> 2
Also the evaluation should take place once user inputs blank line.
My efforts : I created a method attr_accessor which iterates through the array of *secret passed to it, and calls define_method on each attr, creating an instance variable getter and setter for each attribute.
Part of code working :
I made a success in evaluating the expressions and returning string values.
irb : 3+2
Should evaluate to => 5
irb : True
=> True
But still stuck with evaluation of assignment to attributes and unable to dynamically store those values in my interactive irb. Below expected results are not working :
Attribute
irb : abc = 1
=> 1
irb : def = 1
=> 1
irb : abc + def
=> 2
Note - I don't want to use "require 'irb' " or " "require 'pry'". Can this be achieved with simple ruby code ?
My Solution:
class Demo
def self.attr_accessor(*secret)
secret.each do |attr|
define_method(attr) { instance_variable_get("##{attr}") }
define_method("#{attr}=") { |val| instance_variable_set("##{attr}", val) }
end
get_binding
end
def self.method_new(input)
#object = attr_accessor(input)
end
def self.method(secret)
#object = Regexp.new(/\A[\d+\-*\/=. ]+\z/).match(secret.to_s) ? eval(secret) : "Invalid expression"
get_binding
end
def self.simple_method(secret)
#object = secret
get_binding
end
def self.get_binding
binding
end
end
user_input = ''
until user_input == 'q' do
user_input = gets.chomp
if user_input =~ /^.*=.*$/
b2 = Demo.method_new(*user_input)
puts eval('#object', b2)
elsif user_input =~ /\A[\d+\-*\/=. ]+\z/
b3 = Demo.method(user_input)
puts eval('#object', b3)
else
b4 = Demo.simple_method(user_input)
puts eval('#object', b4)
end
end
Expected Result:
irb : 3+2
#note - each result evaluated after user enters blank line
Should evaluate to => 5
Attributes ---
irb : abc = 1
#note - each result evaluated after user enters blank line
=> 1
irb : def = 1
#note - each result evaluated after user enters blank line
=> 1
irb : abc + def( or jkl)
#note - each result evaluated after user enters blank line
=> 2
Actual Result : Output is "Invalid expression" for all other inputs except expressions and simple strings.
I believe, I have partly reached to the solution of above problem. Now I can store the values of attributes in a hash map. I tried accessing these values through keys and thus can easily store and display values for assignments like:
rb : x = 1
=> 1
or
rb : y = 1
But the part of code I have written for evaluating 'x + y' is trying to partition it on operator and then accessing value of each attribute.
I am doing something wrong in line of code marked with comment #faulty. Due to which I got output like
=> x y
I am unable to access key values after partitioning.
Can someone please advise on this piece of code alone ?
Solution:
class Module
def initialize(args)
args.each do |key, value|
# the instance_variable_set method dynamically creates instance variables
# with the key as the name and value as the assigned value
instance_variable_set("##{key}",value)
# define_singleton_method creates a getter method with the same name as the
# key and inside the block you define what it returns
define_singleton_method(key){ value }
#defining the setter method
define_singleton_method("#{key}=") do |val|
instance_variable_set("##{key}", val)
end
end
end
end
class Demo
#var :bar
def self.eval_binary_expr(expr)
if expr =~ /^.*=.*$/
obj = Module.new(:name => expr)
#object1 = eval(obj.name)
get_binding
else
obj = Module.new(:name => expr)
l_operand, op, r_operand = (obj.name).partition(%r{[/*+-]}) #Faulty
if op.empty?
raise ArgumentError, "Invalid operation or no operation in expression: #{expr}"
end
case op
when '/'; then #object1 = (l_operand / r_operand); get_binding
when '*'; then #object1 = (l_operand * r_operand); get_binding
when '+'; then #object1 = (l_operand + r_operand); get_binding
when '-'; then #object1 = (l_operand - r_operand); get_binding
end
end
end
def self.method(secret)
#object2 = Regexp.new(/\A[\d+\-*\/=. ]+\z/).match(secret.to_s) ? eval(secret) : "Invalid expression"
get_binding
end
def self.new_method(secret)
#object3 = secret
get_binding
end
def self.get_binding
binding
end
end
user_input = ''
until user_input == 'q' do
user_input = gets.chomp
if user_input =~ /\A[\w+\-*\/=. ]+\z/
b2 = Demo.eval_binary_expr(user_input)
puts eval('#object1', b2)
elsif user_input =~ /\A[\d+\-*\/=. ]+\z/
b3 = Demo.method(user_input)
puts eval('#object2', b3)
else
b4 = Demo.new_method(user_input)
puts eval('#object3', b4)
end
end
I have a class called PolynomialElements and inside that class I have a method called printElement that has a puts statement that print two variables. The puts statement is printing the variables on different lines. How do I get puts to print the two variables on one line. My code is below, it is line #5 where the puts statement is.
class PolynomialElements
attr_accessor :element, :size
def printElement
puts "#{element}x^#{size}"
end
end
askAgain = true
polyArray = Array.new
while askAgain
puts "How many numbers do you want to enter? "
numString = gets
num = numString.to_i
while num > 0
puts "Enter a value for the Polynomial "
value = gets
polyArray.push(value)
num -= 1
end
sizeOfArray = polyArray.length
polyArray.each do |x|
var = PolynomialElements.new
var.element = x
sizeOfArray -= 1
var.size = sizeOfArray
var.printElement
end
puts "Enter y to enter new number or anything else to quit"
cont = gets
if cont.chomp != "y"
askAgain = false
else
polyArray.clear
end
end
In the while loop change:
value = gets
to:
value = gets.chomp
You will then get:
Enter a value for the Polynomial
3
1x^2
2x^1
3x^0
I have the following code:
def say(msg)
puts "=> #{msg}"
end
def do_math(num1, num2, operation)
case operation
when '+'
num1.to_i + num2.to_i
when '-'
num1.to_i - num2.to_i
when '*'
num1.to_i * num2.to_i
when '/'
num1.to_f / num2.to_f
end
end
say "Welcome to my calculator!"
run_calculator = 'yes'
while run_calculator == 'yes'
say "What's the first number?"
num1 = gets.chomp
say "What's the second number?"
num2 = gets.chomp
say "What would you like to do?"
say "Enter '+' for Addition, '-' for Subtraction, '*' for Multiplication, or '/' for Division"
operation = gets.chomp
if num2.to_f == 0 && operation == '/'
say "You cannot devide by 0, please enter another value!"
num2 = gets.chomp
else
result = do_math(num1, num2, operation)
end
say "#{num1} #{operation} #{num2} = #{result}"
say "Would you like to do another calculation? Yes / No?"
run_calculator = gets.chomp
if run_calculator.downcase == 'no'
say "Thanks for using my calculator!"
elsif run_calculator.downcase == 'yes'
run_calculator = 'yes'
else
until run_calculator.downcase == 'yes' || run_calculator.downcase == 'no'
say "Please enter yes or no!"
run_calculator = gets.chomp
end
end
end
I need it to take the num1 and num2 variables that the user inputs and validate that they are numbers and return a message if they aren't.
I would like to use a Regex, but I don't know if I should create a method for this or just wrap it in a loop.
The Integer method will raise an exception when the given string is not a valid number, whereas to_i will fail silently (which I think is not desired behavior):
begin
num = Integer gets.chomp
rescue ArgumentError
say "Invalid number!"
end
If you want a regex solution, this will also work (although I recommend the method above):
num = gets.chomp
unless num =~ /^\d+$/
say "Invalid number!"
end
You would often see each section written something like this:
ERR_MSG = "You must enter a non-negative integer"
def enter_non_negative_integer(instruction, error_msg)
loop do
puts instruction
str = gets.strip
return str.to_i if str =~ /^\d+$/
puts error_msg
end
end
x1 = enter_non_negative_integer("What's the first number?", ERR_MSG)
x2 = enter_non_negative_integer("What's the second number?", ERR_MSG)
Here's possible dialog:
What's the first number?
: cat
You must enter a non-negative integer
What's the first number?
: 4cat
You must enter a non-negative integer
What's the first number?
: 22
#=> 22
What's the second number?
: 51
#=> 51
x1 #=> 22
x2 #=> 51
This is my first foray into computer programming. I have chosen to learn Ruby, and I am enjoying it quite a bit. However, I am a little confused as to why the answer will not output properly in this bit of code.
def addition_function
puts "Which numbers would you like to add?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 + #n2 == #answer
puts "The sum is... #{#answer}"
end
def subtraction_function
puts "Which numbers would you like to subtract?"
#n1 = gets.chomp.to_i
#n2 = gets.chomp.to_i
#n1 - #n2 == #answer
puts "The answer is... #{#answer}"
end
def multiplication_function
puts "Which numbers would you like to multiply?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 * #n2 == #answer
puts "The answer is... #{#answer}"
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
if response == "add" then
addition_function
end
if response == "subtract" then
subtraction_function
end
if response == "multiply" then
multiplication_function
end
I know this is probably horrible code... but could someone help steer me in the right direction?
Consider this code:
def get_int_values
[gets, gets].map{ |s| s.chomp.to_i }
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values.inject(operator)
puts "The answer is... #{ answer }"
The idea is to follow the "DRY" principle: "DRY" means "Don't Repeat Yourself", which the vast majority of the time, is a really good thing.
To help avoid typing mistakes I'd recommend doing something like:
puts "Would you like to [a]dd, [m]ultiply, or [s]ubtract?"
response = gets.chomp
case response[0].downcase
then change the when clauses to match the first letter of the desired operation.
Which will work unless response is empty. You can figure out how to handle that.
another way to obtain answer, once operator is determined, is answer = gets.to_i.send(operator, gets.to_i)
That's true, but here's why I refactored the code the way I did: If, for some reason, there was a need to operate on more than two values, only one thing has to be changed:
[gets, gets].map{ |s| s.chomp.to_i }
could become:
[gets, gets, gets].map{ |s| s.chomp.to_i }
Or, better, could be transformed to something like:
def get_int_values(n)
n.times.map { gets.chomp.to_i }
end
Nothing else will have to change except to find out how many values are needed.
Now, to do it all right would require different text to alert the user that multiple values are expected, but that's easily done by letting letting the user say how many they want to enter, and then prompting for each gets:
def get_int_values(n)
n.times.map.with_index { |n|
print "Enter value ##{ 1 + n }: "
gets.chomp.to_i
}
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
puts "How many values?"
num_of_values = gets.to_i
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values(num_of_values).inject(operator)
puts "The answer is... #{ answer }"
inject can scale up easily because it doesn't presuppose knowledge about the number of values being operated on.
I think with_index in n.times.map.with_index is an artifact you forgot to delete.
It was deliberate but I like this better:
def get_int_values(n)
1.upto(n).map { |n|
print "Enter value ##{ n }: "
gets.chomp.to_i
}
end
Your assignments are on the wrong side of the statement. You should have answer = n1 * n2,
which is not the same as answer == n1 * n2 (this is a check for equality, using ==). The expression always goes on the right, and the variable the result is assigned to goes on the left -- this is pretty much universal, but not necessarily intuitive coming from algebra.
Also: using an # prior to a variable name differentiates it as an instance variable, or member, of a class. From what you've shown here you don't need to include those, just normally scoped variables are required for this use.
Check out this question for more on that part.
The "#" sigil is used to indicate a class instance variable, you have no class so don't use it.
#n1 + #n2 == #answer
Is a boolean expression evaluating whether #n1 + #n2 is equal to #answer.
It will evaluate to true or false.... but you don't make use of the answer.
What you want is ...
answer = n1 + n2
I strongly recommend you always run Ruby with the -w option. It will save you much much heartache.
Please indent your "end"'s to match your "def" (or "if").
You repeat n1 = gets.chomp.to_i all over the place, do it once and pass the answers as a parameter...
response = gets.chomp
n1 = gets.chomp.to_i
n2 = gets.chomp.to_i
if response == "add" then
addition_function( n1, n2)
elsif...
A few suggestions not mentioned by others:
Shorten your method (not "function") names and use verbs (e.g., add instead of addition_method).
As well as using local variables rather than instance variables (mentioned by others), eliminate them where you can. For example, you could simplify
.
def add
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{answer}"
end
to
def add
puts "Which numbers would you like to add?"
puts "The sum is... #{gets.to_i + gets.to_i}"
end
Notice I've used the Ruby convention of indenting two spaces.
You don't need chomp here (though it does no harm), because "123followed by \n or any other non-digits".to_i => 123.
A case statement would work well at the end (and let's loop until the user chooses to quit):
.
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
case gets.chomp
when "add"
add
when "subtract"
subtract
when "multiply"
multiply
when "quit"
break
end
or just
def quit() break end
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
send(gets.chomp)
end
Here we do need chomp. You could replace loop do with while true do or use other equivalent constructs.
class Calculator
def Calc
puts"==well come to mobiloitte calculator=="
puts "enter the first operand:"
#op1 = gets.chomp
return if #op1=="q"
#o1=#op1.to_i
puts "entre the second operand:"
#op2 = gets.chomp
return if #op2=="q"
#o2=#op2.to_i
strong text puts "enter any one operator of your choice (add,sub,mul,div,mod)"
operator = gets.chomp
case operator
when 'add' then #s=#o1+#o2 ; puts "\n ##o1 + ##o2 =##s"
when 'sub' then #t=#o1-#o2 ; puts "\n ##o1 - ##o2 =##t"
when 'mul' then #l=#o1*#o2 ; puts "\n ##o1 * ##o2 =##l"
when 'div' then #r=#o1/#o2 ; puts "\n ##o1 \ ##o2 =##r"
when 'md' then #d=#o1%#o2 ; puts "\n ##o1 % ##o2 =##d"
else
puts"invalide input"
end
end
end
obj= Calculator.new
$f=obj.Calc
You are using #n1 + #n2 == #answer to try and set the answer. What you want to do is #answer = #n1 + #n2.
= is assignment, == is a comparison operator.
Also, you will need to #n1 = gets.chomp.to_i. This will convert your input to an integer from a string. Do that with #n2 as well.
You also do not need to use the # before each of your variables. That should only be used when you are dealing with classes, which you do not appear to be doing.
print "enter number 1 : "
n1 = gets.chomp.to_f
print "enter number 2 : "
n2 = gets.chomp.to_f
print "enter operator: "
op = gets.chomp
if op == '+'
puts "#{n1} + #{n2} = #{n1 + n2}"
elsif op == '-'
puts "#{n1} - #{n2} = #{n1 - n2}"
elsif op == '*'
puts "#{n1} * #{n2} = #{n1 * n2}"
elsif op == '/'
puts "#{n1} / #{n2} = #{n1 / n2}"
end
puts "Would you like to
0 ---- [exit],
1 ---- [add],
2 ---- [subtract],
3 ---- [multiply],
4 ---- [divide]"
response = gets.chomp
case response.downcase
when '1'
def addition_function
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{n1} + #{n2} = #{answer}"
end
addition_function()
#Subtract
when '2'
def subtraction_function
puts "Which numbers would you like to subtact?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 - n2
puts "The subtraction is... #{n1} - #{n2} = #{answer}"
end
subtraction_function()
#Multiply
when '3'
def multiplication_function
puts "Which numbers would you like to multiply?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 * n2
puts "The multiplication is... #{n1} * #{n2} = #{answer}"
end
multiplication_function()
#Division
when '4'
def division_function
puts "Which numbers would you like to divide?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 / n2
puts "The division is... #{n1} / #{n2} = #{answer}"
end
division_function()
else '0'
puts "Exit! Thank You for using us!"
end
#ruby script to do the calculator
puts " enter the number1"
in1=gets.to_i
puts " enter the number2"
in2=gets.to_i
puts "enter the operator"
op=gets.chomp
case op
when '+'
plus=in1+in2
puts "#{in1+in2}"
#puts "#{plus}"
when '-'
min=in1-in2
puts "#{min}"
when '*'
mul= in1*in2
puts "#{mul}"
when '/'
div=in1/in2
puts "#{div}"
else
puts "invalid operator"
end
begin
puts 'First number:'
a = $stdin.gets.chomp.to_i
puts 'Second number:'
b = $stdin.gets.chomp.to_i
operation = nil
unless ['+', '-', '*', '/', '**'].include?(operation)
puts 'Choose operation: (+ - * /):'
operation = $stdin.gets.chomp
end
result = nil
success = false
case operation
when '+'
result = (a + b).to_s
when '-'
result = (a - b).to_s
when '*'
result = (a * b).to_s
when '/'
result = (a / b).to_s
when '**'
result = (a**b).to_s
else
puts 'There is not such kind of operation'
end
success = true
puts "Результат: #{result}"
rescue ZeroDivisionError => e
puts "You tried to devide number by zero! Error: #{e.message}"
end
if success
puts "\nSuccess!"
else
puts "\nSomething goes wrong :("
end
puts ("plz enter a number :")
num1 = gets.chomp.to_f
puts ("plz enter a another number")
num2 = gets.chomp.to_f
puts ("plz enter the operation + , - , x , / ")
opp = gets.chomp
if opp == "+"
puts (num1 + num2)
elsif opp == "-"
puts (num1 - num2)
elsif opp == "x"
puts (num1 * num2)
elsif opp == "/"
puts (num1 / num2)
else puts ("try again :|")
end