Ruby 设置未初始化的实例变量

Ruby 设置未初始化的实例变量,ruby,class,coding-style,instance-variables,Ruby,Class,Coding Style,Instance Variables,在未初始化的类中使用实例变量并使用其他方法设置它们是否优雅?或者有更好的方法 class Klass def initialize(a) @a = a end def set_b(b) @b = b end end 您这样做是可行的,但Ruby为此定义了attr\u访问器,attr\u阅读器和attr\u编写器 attr\u reader:创建读取“a”的方法 attr\u writer:创建写入“a”的方法 attr\u访问器:创建读写“a”的方法 我认为最

在未初始化的类中使用实例变量并使用其他方法设置它们是否优雅?或者有更好的方法

class Klass
  def initialize(a)
    @a = a
  end

  def set_b(b)
    @b = b
  end
end

您这样做是可行的,但Ruby为此定义了
attr\u访问器
attr\u阅读器
attr\u编写器

attr\u reader
:创建读取“a”的方法

attr\u writer
:创建写入“a”的方法

attr\u访问器
:创建读写“a”的方法

我认为最好的方法是使用
attr\u访问器:a

class Klass
  attr_accessor:a
  def initialize(a)
    @a = a
  end
end
然后你可以做:

k = Klass.new "foo" #example 
k.a = "bar"

与其他语言不同,如果不初始化实例变量,它将始终为
nil
(而在某些其他语言中,可能会得到未定义的内容)

只要
Klass
的其他方法不依赖于实际具有值的实例变量,这应该是可以的

至于getter和setter,有
attr\u访问器
attr\u读取器
attr\u编写器
(请参阅)

Klass类
属性存取器:b
#还有attr_reader和attr_writer
def初始化(a)
@a=a
结束
结束
k=Klass.new:foo
k、 b=:巴
k、 b
#=>:巴
k、 a
#=>用于#的未定义方法“a”(命名错误)
class Klass
  attr_accessor :b
  # there's also attr_reader and attr_writer

  def initialize(a)
    @a = a
  end
end

k = Klass.new :foo
k.b = :bar

k.b
#=> :bar

k.a
#=> undefined method `a' for #<Klass:0x007f842a17c0e0 @a=:foo, @b=:bar> (NoMethodError)