“未定义的方法"错误红宝石 [英] "undefined method" error ruby

查看:43
本文介绍了“未定义的方法"错误红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 ruby​​ 并发现通过其对象访问类全局变量时遇到困难.这是我尝试访问它的方式:

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:

MyController 类中的代码:

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

MyClass 类中的代码:

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

当我打印标准时,输出是:

When I print criteria, the output is:

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

我试图在content"变量中打印数据,所以我尝试了 my_params.content.有了这个,我收到未定义的方法`内容"错误,我理解它,因为我正在尝试使用方法调用约定/语法访问变量.

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.

我想从我的控制器打印@content 变量.是否可以?如何使用变量my_params"从控制器打印内容"?

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"?

推荐答案

仅仅因为 MyClass 有一个名为 @content 的实例变量并不意味着它会自动提供该变量的访问器方法.

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

如果您的类具有该 attr_accessor 行或实际通过其他方法公开实例变量,那么您应该能够访问它.否则,Ruby 实际上不允许您将实例变量名称作为方法直接调用到类的实例.

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.

这篇关于“未定义的方法"错误红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆