0

我更新了这个问题,以更好地反映我需要掌握的问题。下面的例子有点工作,但是我如何访问 Sub 类,然后我在 Base 类中定义了它?在课外打电话不是更好吗?如果是这样,我该怎么做?在这个例子中我遇到的第二个问题是如何获取值以便我可以在另一个类中使用它们。在这里,我将值存储在一个数组中,稍后我需要在另一个类中解包。我应该不能为此使用 proc 吗?

基本上我想要做的是根据它们是否嵌套将方法分类为两个不同的类。

class Sub 

  def initialize(base_class_method)
     @base_class_method = base_class_method
     @sub_methods = []
  end

   # omitted code here

  def base_class_method
     @base_class_method
  end

  def sub_actions(method)
     @sub_methods << method
  end

  def return_sub_methods
    @sub_methods
  end

  def method_missing(sub_method, &block)
    if sub_method
      sub_method
    else
      super
    end
  end
end

class Base

  def initialize
    @base_methods = []
  end

  # omitted code here

  def base_actions(method)
    @base_methods << method
  end

  def return_base_methods
    @base_methods
  end

  def method_missing(method, &block)
    if block_given?
      Sub.new(method).instance_eval(&block)
    elsif method
    base_actions(method)
    else
      super
    end
  end
end


base = Base.new
base.instance_eval do
  something1
  something_with_a_block do
    something_inside_block1_1
    something_inside_block1_2
  end
  something2
  something_with_a_block2_2 do
  something_inside_block2_1
  end
end

p base.return_base_methods   #=> [:something1, :something2]   works!
4

1 回答 1

0

你可以做这样的事情。

class Test
  # reserved method to instantiate object
  def initialize(a,b,c)
    @a = a
    @b = b
    @c = c
  end

  # getters
  def a
    @a
  end

  def b
    @b
  end

  def c
    @c
  end

  def abc
    [@a, @b, @c] # returns an array
  end

  # setters
  def a=(var)
    @a = var
  end

  def b=(var)
    @b = var
  end

  def c=(var)
    @c = var
  end

  # set values all at once
  def update(a, b, c)
    @a = a
    @b = b
    @c = c
  end
end

z = Test.new('something','something','something')
z.update('something!','nothing!',"a thing!")
z.a
z.b
z.c
z.a = 'wow, new value!'
于 2012-06-14T03:28:18.377 回答