gpt4 book ai didi

ruby - 在 self.method 中看起来像这个 @my_variable 的实例变量是什么意思?

转载 作者:数据小太阳 更新时间:2023-10-29 08:02:53 25 4
gpt4 key购买 nike

我不明白类方法中的实例变量的作用。下面的代码对我来说毫无意义。类方法如何操作实例变量?我什至可以在没有实例的情况下调用类方法。

def self.schema
return @schema if @schema
DB.table_info(table) do |row|
@schema[row['name']] = row['type']
@schema
end

编辑:在@Aetherus 的回答后跟进问题。
以下代码示例中的 first_name 是什么?为什么我不能将它作为类变量访问,因为它在类范围内?为什么这 3 种方法都会给我错误?

   class Person
#class scope
first_name = "jimmy"

# expected error beacuse it would treat as local variable
def print_name
#instance scope
first_name
end

#to my understanding this should work, but it doesnt. i dont know why
def print_name_2
#instance scope
#with self.class i should be able to access class scope?
self.class.first_name
end

#to my understading this should work, but it doesnt. I dont know why.
def self.print_name
#class scope
#inside class scope, i should able to access first_name?
first_name
end

end

最佳答案

简而言之,这些实例变量属于类,而不是属于该类的实例。

要理解它,您需要更多地了解 Ruby。

类是对象

在 Ruby 中,所有的类都是 Class 类型的对象。

String.class  #=> Class
Array.class #=> Class
Class.class #=> Class

并且可以通过实例化Class来定义匿名类

foo = Class.new do
# Here you can define methods
end

foo.new #=> an instance of an anonymous class

因为类是对象,它们也可以有实例变量。

作用域之门

触发作用域切换的关键字有4个:module, class, def and do (for blocks ).这里我只显示classdef

# in the scope of main

class Foo
# in the scope of Foo

def self.bar
# still in the scope of Foo
end

# in the scope of Foo

def bar
# in the scope of an instance of Foo
end

# back to the scope of Foo again
end

# back to the scope of main

作用域中定义的实例变量属于该作用域的当前对象(又名self)。在前面的示例中,如果您在 Foo 范围内定义了一个实例变量,则该实例变量属于该范围的 self,即类 Foo

关于ruby - 在 self.method 中看起来像这个 @my_variable 的实例变量是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com