Home > database >  Assign value of a class to another class
Assign value of a class to another class

Time:11-21

I was wonder if it is possible to assign value of a class to another class like this example.

class Test1
  attr_accessor :num1, :num2
  def initialize
    @num1 = num1
    @num2 = num2
  end
end

class Test2
  attr_accessor :number1, :number2
  def initialize
    @number1 = number1
    @number2 = number2
  end
end

num = Test1.new(1, 2)
number = Test2.new(11, num)

number.number2 = temp
puts temp.num2 

I get an "`initialize': wrong number of arguments (given 2, expected 0) (ArgumentError)" message. So i don't know if i get error in the code or it is not possible to assign class to another class this way.

CodePudding user response:

You need to define your initialize method to take num1 and num2, and number1 and number2 as arguments. Otherwise it is assigning the return value of the accessor methods to the instance variables, and those methods are just returning nil.

class Test1
  attr_accessor :num1, :num2
  def initialize(num1, num2)
    @num1 = num1
    @num2 = num2
  end
end

class Test2
  attr_accessor :number1, :number2
  def initialize(number1, number2)
    @number1 = number1
    @number2 = number2
  end
end

You will still get an error resulting from temp not being defined before you attempt to use it.

  •  Tags:  
  • ruby
  • Related