如何在语法上调用一个在另一个方法中占用块的方法?

时间:2015-07-08 21:59:49

标签: ruby methods block yield

所以我是Ruby的新手,我希望让我的代码更整洁,更清晰。基本上我在课堂上有这些方法。我制作了反向抛光记谱计算器。现在我在理论上知道“不要重复自己”,但正如您在plus minus dividetimes方法中所看到的那样。基本上唯一改变的是+, - ,/,*。我想知道解决这个问题的最佳方法是什么?首先,这是代码。我的一些想法如下。

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

基本上,我正在考虑制作另一个方法end_calc(),它采用一个块(?)。我想知道那会是什么样子。例如,这就是我的想法。

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

基本上在方法plus minus等中,我只需要调用end_calc以及必要的+ - / *符号。如何在语法上编写它以便将+方法插入end_calc?或者我应该怎么去学习以了解如何做到这一点?是否还有其他什么可以做得更有效,我还不知道呢?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

Sub NewControls()
    Dim frm As Form
    Dim ctlLabel As Control, ctlText As Control
    Dim intDataX As Integer, intDataY As Integer
    Dim intLabelX As Integer, intLabelY As Integer

    ' Create new form with Orders table as its record source.
    Set frm = CreateForm
    frm.RecordSource = "Orders"
    ' Set positioning values for new controls.
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100
    ' Create unbound default-size text box in detail section.
    Set ctlText = CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ' Create child label control for text box.
    Set ctlLabel = CreateControl(frm.Name, acLabel, , _
         ctlText.Name, "NewLabel", intLabelX, intLabelY)
    ' Restore form.
    DoCmd.Restore
End Sub

此外,我认为您应该将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 重命名为times,因为方法multiply经常用于重复代码块数次,这可能会导致误解。