将动态值附加到ruby实例变量

时间:2014-10-08 06:08:18

标签: ruby

我知道这段代码看起来不太好,但我只是想解释一下我的要求。我想知道是否有任何好的或替代方法。

实际上,我想创建一个新的堆栈,并且每当一个堆栈达到其容量时。我希望通过像@stack_1这样递增@stack_2来跟踪创建的堆栈数量,例如@number += 1@stack_@number ...对于每个堆栈,我想维护一个@current_position指针,该指针特定于@stack_2具有@current_position_2的每个堆栈。所以我想创建动态实例变量。

示例:

def initialize
  @number = 1
  @stack+"#{@number}" = Array.new(10)
  @current_position_"#{@number}" = 0
end

输出应该类似于@stack1 = Array.new(10)
假设我增加@number += 1的值,它应该看起来像@stack2 = Array.new(10)

3 个答案:

答案 0 :(得分:2)

我建议你使用Hash Map

而不是数组
@stack = Hash.new

@stack[@number] = <Your Array>

如果@number相同,请小心,您的阵列将被替换..

有关哈希映射http://www.ruby-doc.org/core-1.9.3/Hash.html

的更多信息

答案 1 :(得分:1)

你可以这样做:

instance_variable_set("@stack#{@number}", Array.new(10, :a))
@stack1
  #=> [:a, :a, :a, :a, :a, :a, :a, :a, :a, :a]

instance_variable_set("@stack#{@number+1}", Array.new(10, :b))
@stack2
  #=> [:b, :b, :b, :b, :b, :b, :b, :b, :b, :b]

instance_variable_set("@current_position_#{@number}", 0)
@current_position_1
  #=> 0

答案 2 :(得分:1)

您可以创建一个在内部跟踪其状态的Stack类,而不是创建实例变量来从外部跟踪堆栈的状态。这是一个非常简单的问题:

class StackOverflow < StandardError; end

class Stack
  def initialize
    @stack = []
  end

  def position
    @stack.size
  end

  def full?
    position == 2 # small size for demonstration purposes
  end

  def push(obj)
    raise StackOverflow if full?
    @stack << obj
  end
end

stack = Stack.new
stack.push "foo"
stack.full?       #=> false

stack.push "bar"
stack.full?       #=> true

stack.push "baz"  #=> StackOverflow

拥有一个工作堆栈,你可以构建类似StackGroup的东西来处理多个堆栈:

class StackGroup
  attr_reader :stacks

  def initialize
    @stacks = [Stack.new]
  end

  def push(obj)
    @stacks << Stack.new if @stacks.last.full?
    stacks.last.push(obj)
  end
end

stack_group = StackGroup.new
stack_group.push "foo"
stack_group.push "bar"
stack_group.stacks.size #=> 1

stack_group.push "baz"  # no error here
stack_group.stacks.size #=> 2

stack_group.stacks
#=> [#<Stack:0x007f9d8b886b18 @stack=["foo", "bar"]>,
#    #<Stack:0x007f9d8b886a50 @stack=["baz"]>]