oj5th
oj5th

Reputation: 1409

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?

Upvotes: 1

Views: 374

Answers (2)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

What you should do is create @input as and array and iterate over it to display all the results.

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}

Upvotes: 1

jan.zikan
jan.zikan

Reputation: 1316

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'

Upvotes: 1

Related Questions