记住ruby

时间:2016-10-24 15:05:32

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

我在下面有这个示例课。

class MyClass
  def initialize(options = {})
    @input = options[:input]
  end

  def trigger
    # I want to remember previous input value if this method called.
    input
  end
end

如何存储或记住先前输入的先前值?例如。

my_class = MyClass.new(input: "first")
my_class.trigger
=> first

如果我打电话:

my_class.input = "second"

我想记住以前的值输入"fisrt"。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

你应该做的是创建@input as和array并迭代它以显示所有结果。

class MyClass
  attr_accessor :input

  def initialize(options = {})
    @input = []
    @input << options[:input]
  end

  def input=(item)
    @input.unshift(item)
  end

  def trigger
    # I want to remember previous input value if this method called.
    @input.first
  end
end

my_class = MyClass.new(input: 'first')
my_class.input = "second"

my_class.input.each {|i| puts i}

答案 1 :(得分:1)

当您调用方法触发器时,需要另一个实例变量来保存分配给input变量的值。

class MyClass
  attr_writer :input

  def initialize(options = {})
    @input = options[:input]
  end

  def trigger
    @triggered_input = @input
  end

  def input
    @triggered_input
  end
end

my_class = MyClass.new(input: 'first')
my_class.input #=> nil
my_class.trigger #=> 'first'

my_class.input = 'second'
my_class.input #=> 'first'
my_class.trigger #=> 'second'
my_class.input #=> 'second'