Sathish
Sathish

Reputation: 419

Passing object properties to function call in Ruby class

def printer_outside_class(value)
 puts value
end

class Prints
 attr_accessor :value
 def initialize(a)
   @value = a
 end
 printer_outside_class(@value)
end 

Prints.new(100)

I do not get any output instead it throws a warning "instance variable @value not initialized". Ruby executes the class line by line so before the initialize function gets called, printer_outside_class(value) gets called.

Is it possible to somehow pass the variable value to the outer printer_outside_class(@value) function call? value should be passed from outside and it need not be via constructor.

Note: I am free to change the constructor, add arbitrary code to Prints class, add a new class and have the liberty to call Prints class however I want. However, I won't be able to move the function call printer_outside_class(@value) inside a function definition.

Upvotes: 0

Views: 153

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

If I properly understood the question, the way to go would be to use instance variable on class level:

def printer_outside_class(value)
  puts value
end

class Prints
  @value = 100
  def self.value; @value; end
  def self.value=(neu); @value = neu; end

  def initialize(a)
     self.class.value = a
     printer_outside_class(a)
   end
  printer_outside_class(value)
end

Prints.new(123)

Upvotes: 1

Related Questions