0

I am learning ruby and finding difficulty in accessing a class global variable through its object. Here is how I was trying to access it:

Code inside MyController class:

class MyController
    def create
       my_params = MyClass.new params
       p my_params.content
    end
end

Code inside MyClass class:

class MyClass
    def initialize(content)
      @content = content
    end
end

When I print criteria, the output is:

"#<MyClass:0x007fc473bfda58 @content={\"key1\"=>value1, \"key2\"=>value2}>"

I am trying to print the data inside "content" variable and so I tried my_params.content. With this I am getting "undefined method `content" error and I understand its because I am trying access a variable using method calling convention/syntax.

I want to print @content variable from my controller. Is it possible? How do I print "content" from my controller using the variable "my_params"?

Leo Correa
  • 19,131
  • 2
  • 53
  • 71
tech_human
  • 6,592
  • 16
  • 65
  • 107

1 Answers1

1

Just because MyClass has an instance variable called @content doesn't meant that it will automatically provide accessor methods for that variable.

class MyClass
  attr_accessor :content
end

If your class has that attr_accessor line or actually exposes the instance variable through some other method then you should be able to access it. Otherwise, Ruby doesn't actually allow you to call the instance variable name as a method directly to the instance of a class.

Leo Correa
  • 19,131
  • 2
  • 53
  • 71