Ruby:将对象分配给变量
我有一段我不懂的Ruby代码:Ruby:将对象分配给变量,ruby,class,instance,Ruby,Class,Instance,我有一段我不懂的Ruby代码: Line = Struct.new(name, "example") // what happens here? def foo(lines) lines.map { |z| Line.new(name, z[:specific]) // equal to 'Struct.new'? } end 这是否意味着Line现在是Struct的别名?或者这里还会发生什么?行是一个新类,由Struct.new返回Struct是一个帮助器类,它允许您轻
Line = Struct.new(name, "example") // what happens here?
def foo(lines)
lines.map { |z|
Line.new(name, z[:specific]) // equal to 'Struct.new'?
}
end
这是否意味着
Line
现在是Struct
的别名?或者这里还会发生什么?行
是一个新类,由Struct.new
返回Struct
是一个帮助器类,它允许您轻松地使用访问器方法创建类,以字段的名称作为构造函数参数。一开始可能会让人困惑,但在Ruby中,类只是另一种类型的对象,因此它们可以由方法创建
您可以在此处获得有关Struct
工作原理的参考:
这是否意味着Line
现在是Struct
的别名
不,那大概是
Line = Struct
foo = gets
Struct
name
发送到self
new
发送到1中返回的对象,第一个参数是2中返回的对象,第二个参数是文本字符串“example”
行
Line = Struct
foo = gets
gets
不会一次又一次地被调用,每次您取消引用foo
时,当您分配给foo
时,它会被调用一次,然后foo
包含对gets
返回的对象的引用
此外,即使它的工作方式与您似乎认为的一样,那么它仍然不等于
Struct.new
,而是等于Struct.new(name,“example”).new
,因为这是行的赋值右侧的表达式(但是,正如我所说,它不是这样工作的)
class Line
def initialize(example, name)
@example = example
@name = name
end
def name=(name)
@name = name
end
def name
@name
end
def example=(example)
@example = example
end
def example
@example
end
end
当您看到Line.new
时,只需将其视为Line
类的一个实例。Sruct
只是创建行
类的一种更快的方法