gpt4 book ai didi

Ruby 对象与哈希

转载 作者:行者123 更新时间:2023-12-02 15:12:37 26 4
gpt4 key购买 nike

下面的代码片段返回一个对象。

class Person
def initialize(name, gender)
@name = name
@gender = gender
end
end
x = Person.new("Dan", "M")
=> #<Person:0x007f6f96600560 @name="Dan", @gender="M">
  • 一个对象有什么区别< ... >和一个散列 { ... } ?为什么 Ruby 类不只返回哈希值?
  • 什么是 0x007f6f96600560在对象中?我很确定这不是 object_id .

最佳答案

对象 → 哈希

来自优秀的书"Ruby under the microscope"帕特·肖内西:

Every Ruby object is the combination of a class pointer and an array of instance variables.

Here描述有点长:

A user-defined Ruby object is represented by a structure called an RObject, and is referred to by a pointer called VALUE.

Inside RObject, there is another structure called RBasic, which all Ruby values will have.

Aside from the RBasic structure, RObject also contains numiv, a count of how many instance variables the object has, ivptr, a pointer to an array of values of the instance variables, and iv_index_tbl, which is a pointer to a hash table stored in the object’s associated RClass structure that maps the name/identity of each instance variable to its position in the ivtpr array.

从任何 Ruby 对象,都可以 extract a hash of instance variables :

class Object
def instance_variables_hash
Hash[instance_variables.map { |name| [name, instance_variable_get(name)] } ]
end
end

以你的例子:

x.instance_variables_hash
=> {:@name=>"Dan", :@gender=>"M"}

哈希 → 对象 ?

但是您不可能从这个散列中创建 x,因为您遗漏了一条关键信息:x 是哪个类的实例?

例如,您不知道可以发送给 x 的方法:

class Dog
def initialize(name, gender)
@name = name
@gender = gender
end

def bark
puts "WOOF"
end
end

person = Person.new("Dan", "M")
dog = Dog.new("Dan", "M")

p person.instance_variables_hash
# {:@name=>"Dan", :@gender=>"M"}
p dog.instance_variables_hash == person.instance_variables_hash
# true
person.bark
# undefined method `bark' for #<Person:0x007fb3b20ed658 @name="Dan", @gender="M">

object_id

从检查字符串中获取 object_id :

"0x007f6f96600560".sub('0x','').to_i(16)/2
#=> 70058620486320

然后返回:

"0x" + (70058620486320 * 2).to_s(16).rjust(14,'0')
#=> "0x007f6f96600560"

关于Ruby 对象与哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744277/

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