0

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] 
1
  • This is expected because case 1 is a value and case 2 is a reference. You can only access object methods by referencing the object. Commented Mar 4, 2019 at 18:03

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this works fine but my use case is something like what if B.new.kick raises an error I will not get any data. My use case is I want to store the data in array in runtime even if kick method raises an exception I have data in it.
@SantoshMohanty, you will not get any data anyway if error will be raised in a kick method.
@SantoshMohanty: if your version of B#kick raises an error, the program will crash just as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.