Clearly, you can directly use irb as a calculator. However, I'm learning Ruby, so I thought it would be fun to program a simple integer calculator. It's a great little example of a read-eval-print loop.
The calculator accepts input expressions of the form:
<non-negative integer> <op> <non-negative integer>
where op is one of:
- +
- addition
- -
- subtraction
- *
- multiplication
- /
- division
- %
- modulo
- ^
- power
calc.rb
#!/usr/bin/env ruby def evaluate(arg0, op, arg1) ans = case op when '+' arg0 + arg1 when '-' arg0 - arg21 when '/' arg0 / arg1 when '*' arg0 * arg1 when '%' arg0 % arg1 when '^' arg0 ** arg1 else # should never happen "unknown op #{op}" end end def parse_expression(line) regex = /\s*(\d+)\s*([+-\/*%^])\s*(\d+)\s*/ expr = line.match(regex) end def eval_loop while true print 'calc> ' $stdout.flush line = gets.chomp if line == 'exit' break end expr = parse_expression(line) if expr arg0, op, arg1 = expr.captures puts evaluate(arg0.to_i, op, arg1.to_i) else puts 'invalid expression' end end end puts "enter 'exit' to quit the program'" eval_loop
example
./calc.rb enter 'exit' to quit the program' calc> 1 + 2 3 calc> 2 ^ 8 256 calc> 400 % 92 32 calc> exit
No comments:
Post a Comment