ruby - How to syntactically call a method that takes a block in another method? -
so i'm new ruby , i'm looking make code little neater , cleaner looking. have these methods in class. made reverse polish notation calculator. know in theory "don't repeat yourself" can see in plus
minus
divide
, times
methods do. thing changes +, -, /, *. i'm wondering best way go fixing that? start, here's code. of thoughts below.
class rpncalculator def initialize @calculator = [ ] end def push(num) @calculator << num end def plus value = @calculator[-2].to_f + @calculator[-1] @calculator.delete_at(-2) @calculator.delete_at(-1) @calculator << value end def minus value = @calculator[-2].to_f - @calculator[-1] @calculator.delete_at(-2) @calculator.delete_at(-1) @calculator << value end def divide value = @calculator[-2].to_f / @calculator[-1] @calculator.delete_at(-2) @calculator.delete_at(-1) @calculator << value end def times value = @calculator[-2].to_f * @calculator[-1] @calculator.delete_at(-2) @calculator.delete_at(-1) @calculator << value end
basically, i'm thinking make method end_calc()
takes block(?). i'm wondering like. example thinking about.
def end_calc(&block) value = @calculator[-2].to_f &block @calculator[-1] @calculator.delete_at(-2) @calculator.delete_at(-1) @calculator << value end def plus end_calc(+) end
basically in methods plus
minus
etc, call end_calc plus necessary +
-
/
*
sign. how can write syntactically +
method inserted end_calc
? or should go studying in order understand how that? there may more effective not know yet?
you can use following code:
class rpncalculator def initialize @calculator = [] end def push(num) @calculator << num end def plus do_operation(:+) end def minus do_operation(:-) end def divide do_operation(:/) end def times do_operation(:*) end private def do_operation(operation) operand_2, operand_1 = @calculator.pop, @calculator.pop value = operand_1.to_f.send(operation, operand_2) @calculator << value end end
also, think should rename times
multiply
, because method times
used repeat block of code several times , may cause misunderstanding.
Comments
Post a Comment