araratan araratan - 1 month ago 6
Ruby Question

remember previous input value in ruby

I have this sample class below.

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


How can I store or remember the previous value that was previously input? For example.

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


If I call:

my_class.input = "second"


I want to remember the previous value input which is
"fisrt"
. How can I achieve this?

Answer

You need another instance variable to persist the value that was assigned to input variable when you call the method trigger.

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'