当然,有时候你可以使用对象和哈希表来完成相同的事情。像这样在对象中存储键值对:
[3] pry(main)> class Person
def initialize(name, gender)
@name = name
@gender = gender
end
end
[3] pry(main)* => :initialize
[4] pry(main)> x = Person.new("Dan", "M")
=> #<Person:0x00000003708098 @gender="M", @name="Dan">
[13] pry(main)> y = Person.new("Peter", "M")
=> #<Person:0x0000000391fca0 @gender="M", @name="Peter">
[22] pry(main)> z = {name: "Maria", gender: "F"}
=> {:name=>"Maria", :gender=>"F"}
但是,从类/对象和哈希的定义来看,这些对象并不能完全发挥面向对象编程语言的全部功能:
Ruby is a perfect Object Oriented Programming Language. The features
of the object-oriented programming language include:
Data Encapsulation:
Data Abstraction:
Polymorphism:
Inheritance:
These features have been discussed in Object Oriented Ruby.
An object-oriented program involves classes and objects. A class is
the blueprint from which individual objects are created. In
object-oriented terms, we say that your bicycle is an instance of the
class of objects known as bicycles.
Take the example of any vehicle. It comprises wheels, horsepower, and
fuel or gas tank capacity. These characteristics form the data members
of the class Vehicle. You can differentiate one vehicle from the other
with the help of these characteristics.
A vehicle can also have certain functions, such as halting, driving,
and speeding. Even these functions form the data members of the class
Vehicle. You can, therefore, define a class as a combination of
characteristics and functions.
还有一个哈希:
哈希是一组键值对,例如:"员工" => "薪资"。它类似于数组,但索引是通过任意对象类型的任意键来完成的,而不是整数索引。
因此,为了存储数据,我建议您使用哈希。
另一方面,正如评论中所示,对象表示中出现的数字是对象ID,但添加了一些操作:
1)按位左移:
5 << 1 # gives 10
2) 转换为十六进制
(10).to_s(16)
"a"
pry(main)> x = Person.new("Dan", "M")
=> #<Person:0x00000003708098 @gender="M", @name="Dan">
[5] pry(main)> x.object_id
=> 28852300
[8] pry(main)> (x.object_id << 1 ).to_s(16)
=> "3708098"
最后,在Ruby中,您可以通过以下方式获取对象的哈希表示:
x.instance_variables.each {|var| hash[var.to_s.delete("@")] = x.instance_variable_get(var) }
0x00...
是(object_id << 1).to_s(16)
的结果,其中object_id
左移一位后转化成 16 进制。关于面向对象编程中的对象有很多书籍已经写得很详细了。你不应该期望在 SO 上得到此类问题的答案,因为人们需要花费数年时间并阅读许多书籍才能理解。 - Aleksei MatiushkinHash
进行子类化,并将实例变量名和值存储为键值对。事实上,JavaScript的工作方式有些类似。 - sawa