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是一个帮助器类,它允许您轻

我有一段我不懂的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
是一个帮助器类,它允许您轻松地使用访问器方法创建类,以字段的名称作为构造函数参数。一开始可能会让人困惑,但在Ruby中,类只是另一种类型的对象,因此它们可以由方法创建

您可以在此处获得有关
Struct
工作原理的参考:

这是否意味着
Line
现在是
Struct
的别名

不,那大概是

Line = Struct
foo = gets
  • 取消引用常量
    Struct
  • 将不带参数的消息
    name
    发送到
    self
  • 将带有两个参数的消息
    new
    发送到1中返回的对象,第一个参数是2中返回的对象,第二个参数是文本字符串
    “example”
  • 分配在3中返回的对象。到常量
  • 不,Ruby中的作业不是这样的。在Ruby中,不将表达式分配给变量,先对表达式求值,然后将求值结果分配给变量一次

    也就是说,如果你做了

    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
    只是创建
    类的一种更快的方法