这是我到目前为止所做的,它不工作:
class Couple(o,t)
one = o
two = t
end
couple1 = Couple.new(10, "Ten")
p couple1.one
p couple1.two
不知道为什么不工作?
定义类不像定义函数那样工作,你必须在它们上面定义使用内部变量的函数,并且初始化器告诉它在调用。new
时该做什么attr_accessor帮助设置函数和变量。最简单的方法是使用像
这样的类class Couple
attr_accessor :one, :two
end
couple1 = Couple.new
couple1.one = 10
couple1.two = "Ten"
p couple1.one
p couple1.two
要使用新函数用几个变量来initialize
类,您可以定义该函数,并给出如下所示的类定义
class Couple
attr_accessor :one, :two
def initialize(one, two)
@one = one
@two = two
end
end
couple1 = Couple.new(10, "Ten")
p couple1.one
p couple1.two
如果您只需要保存一对项,则使用Struct。它是一个简单的类生成器,只包含变量和访问器,不包含其他任何东西(类似于C/c++的Struct)。
Couple = Struct.new(:one, :two)
# Or more idiomatically
class Couple < Struct.new(:one, :two)
def to_s
"one: #{self.one}, two: #{self.two}"
end
end
couple1 = Couple.new(10, 'ten')
puts couple1 # one: 10, two: ten
couple1.one = 100
puts couple1 # one: 100, two: ten
同时,Ruby中一个非常有趣的事情是类数据/成员,无论是实例的还是类/静态的都是"私有的"——你只能通过访问器方法从外部访问它们,而不是直接访问,Ruby给了你用宏atrr_accessor
, attr_reader
和attr_writer
快速生成这些方法的可能性。
class Couple
one = 'o'
two = 't'
end
p Couple.one # NoMethodError: undefined method `one' for Couple:Class
class Couple
def initialize(one, two)
@one = one
@two = two
end
end
c = Couple.new(10, 'ten')
p c.one # undefined method `one' for #<Couple:0x936d2d4 @one=10, @two="ten">
您需要使用attr_reader
读取或attr_accessor
读取/写入来访问类变量。你的类应该是这样的:
class Couple
attr_accessor :one, :two
def initialize(one, two)
@one = one
@two = two
end
end
在本例中,使用attr_accessor
将创建one, one=, two, two=
方法。如果您要使用attr_reader
,它将创建one, two
方法。
使用上面的示例代码,您可以有:
couple = Couple.new(5, 6)
p couple.one # Outputs 5
p couple.two # Outputs 6
couple.one = 7
p couple.one # Outputs 7
还有attr_writer
,它将为您提供one=, two=
方法,但这不是您在这种情况下要寻找的。