如何用Ruby中的文本生成代码

如何用Ruby中的文本生成代码,ruby,metaprogramming,block,static-methods,dsl,Ruby,Metaprogramming,Block,Static Methods,Dsl,我有没有办法扭转这种局面: SomeModule.some_method do choos_one_from 1..10 then_multiply_it_by 2 then_multiply_it_by 5 then_divide_it_by :picked_number then_subtract 7 did_you_get 3 end 为此: (1..10).all? do |number| ((number * 2 * 5) / number) - 7 ==

我有没有办法扭转这种局面:

SomeModule.some_method do
  choos_one_from 1..10
  then_multiply_it_by 2
  then_multiply_it_by 5
  then_divide_it_by :picked_number
  then_subtract 7
  did_you_get 3
end
为此:

(1..10).all? do |number|
  ((number * 2 * 5) / number) - 7 == 3
end
?

我尝试为每一个可能的方法(从中选择一个,然后乘以…)定义方法,这些方法接受一个参数并对其进行处理,但是当产生块时,它会产生值,但我真的不知道如何组合它们,以便我可以得到第二段代码


编辑:我觉得我必须制作一些类似于DSL的东西

您可能需要这样的东西:

module Mathisizer

  def when_i
    Mathisizer::Builder.new
  end

  class Builder
    attr_accessor :range, :choosen_number

    def new
      @operations = []
    end

    def choose_one_from(range)
      self.range = range

      # Randomly determine the number from the range
      # self.choosen_number = ...

      self
    end

    def then_multiply_it_by(n)
      @operations << MultiplicationOperation.new(n)
      self
    end

    def then_add(n)
      @operations << AdditionOperation.new(n)
      self
    end

    def did_you_get?(n)
      x = self.result

      x == n
    end

    def result
      x = choosen_number;

      @operations.each do |operation|
        x = operation.invoke(x)
      end

      x
    end
  end

  class BaseOperation
    def new(n)
      @number = n
    end

    def invoke(n)
      raise 'Base classes must implement invoke(n) -> number'
    end
  end

  class MultiplicationOperation < BaseOperation
    def invoke(x)
      return @number * x
    end
  end

  class AdditionOperation < BaseOperation
    def invoke(x)
      return @number + x
    end
  end

end

基本上,您可以创建一个“构建器”对象,它提供了一个用于创建数学运算对象的流畅API。

但是,如果我不知道“然后乘以它”、“然后除以它”的顺序,该怎么办。如何在Mathesizer.new中创建正确的链接?@user2128702这些方法正在返回self,因此顺序不正确matter@GregBurghardt所以,“self”返回整个Mathesizer对象?@GregBurghardt我想我没有得到它。我只有一个乘数属性。我不知道如何分配它,如果我有几个他们之间的其他行动。正如您所知,不同的操作具有不同的优先级。
self
变量返回Mathisizer的实例。还有,我明白你说的运算顺序,这对数学来说有点重要。您可以维护一系列操作。每个操作都是它自己的类,每个操作类都包含一个通用接口。让我再考虑一下。
Mathisizer.when_i
  .choose_one_from(1..10)
  .then_multiply_it_by(5)
  .did_you_get?(3)