[英]Accessing instance variable in rails and ruby
I am new to ruby and rails and sometimes I still get confused between these two. 我是红宝石和Rails的新手,有时我仍然对这两者感到困惑。 I have tried to call an instance variable by adding a name of the instance variable after an object(john.name), and I hope that the result would be John. 我试图通过在对象(john.name)之后添加实例变量的名称来调用实例变量,我希望结果是John。 Unfortunately NoMethodError appears. 不幸的是NoMethodError出现。 So I searched for an answer and found out that you can use instance_variable_get method to do this. 因此,我搜索了一个答案,发现可以使用instance_variable_get方法执行此操作。 However, I believe that it is possible to do this in RAILS when you want to access the instance variable of an object in VIEWS. 但是,我相信当您要在VIEWS中访问对象的实例变量时,可以在RAILS中执行此操作。
class Person
def initialize(name)
@name = name
end
end
john = Person.new("John")
puts john.instance_variable_get(:@name)
=> John
puts john.name
=> NoMethodError
Use attr_reader
to read the value of an instance variable 使用attr_reader
读取实例变量的值
class Person
attr_reader :name
def initialize(name)
@name = name
end
end
john = Person.new("John")
john.name #=> "John"
attr_reader
adds a getter method to the class, in this case 在这种情况下, attr_reader
将getter方法添加到类中
def name
@name
end
Hope that helps! 希望有帮助!
You need to define the method to access your instance variable. 您需要定义访问实例变量的方法。
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
Or you can simply add attr_accessor which will set getter and setter methods 或者您可以简单地添加attr_accessor,它将设置getter和setter方法
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.