Santosh Mohanty
Santosh Mohanty

Reputation: 482

How to pass a instance/accessor variable in ruby to another class and get data stored in respective variable?

Referring to the below code is there a way that I can pass the variable row from class A to class B#kick and get the data stored?

class A
  attr_accessor :row

  def fetch
    B.new.kick(self.row)
    puts row.inspect
  end
end

class B
  def kick(x)
    x = [3,4]
  end
end

@test = A.new.fetch
expect(@test.row).to eql([3,4])

Current O/P => nil

However If I pass self and assign that works , but I dont want to use this approach: Working Code

class A
  attr_accessor :row

  def fetch
    B.new.kick(self)
    puts row.inspect
  end
end

class B
  def kick(x)
    x.row = [3,4]
  end
end

@test = A.new.fetch
#=> [3, 4]

Upvotes: 0

Views: 156

Answers (1)

Fabio
Fabio

Reputation: 32445

Short version:
x = [3, 4] will create new instance of array and saves to x variable, where row will still reference to the original value(or no value nil).

Another approach could be the kick method to return "kicked" value.

class A
  def fetch
    @row = B.new.kick
    puts row.inspect
  end
end

class B
  def kick(x)
    [3,4]
  end
end

If you want to follow object-oriented programming principle "Tell, don't ask" you can try visitor pattern approach.

class A
  def fetch
    B.new.kick(self)
    puts row.inspect
  end

  def save(row)
    @row = row
  end
end

class B
  def kick(x)
    x.save([3,4])
  end
end

Upvotes: 3

Related Questions