所以假设我有这个(不工作):
class User description = "I am User class variable" def print puts description end end
解决方法
在您的情况下,描述只是局部变量.您可以使用特殊字符@,@ @,$更改此范围:
a = 5 defined? a => "local-variable" @a = 5 defined? @a => "instance-variable" @@a = 5 defined? @@a => "class variable" $a = 5 defined? $a => "global-variable"
为了您的目的,我认为可能是通过这种方式使用
class User def initialize(description) @description = description end def print puts @description end end obj = User.new("I am User") obj.print # => I am User