开发者

Why does hash.keys.class return Arrays?

开发者 https://www.devze.com 2023-03-12 10:48 出处:网络
New to Ruby, I\'m just missing something basic here. Are the keys in a Hash considered an Arra开发者_如何学编程y unto themselves? Yes, Hash#keys returns the hash\'s keys as a new array, i.e., the hash

New to Ruby, I'm just missing something basic here. Are the keys in a Hash considered an Arra开发者_如何学编程y unto themselves?


Yes, Hash#keys returns the hash's keys as a new array, i.e., the hash and the array returned by Hash#keys are completely independent of each other:

a = {}
b = a.keys
c = a.keys

b << :foo

a   # still {}
b   # [:foo]
c   # still []

a[:bar] = :baz

a   # {:bar => :baz}
b   # still [:foo]
c   # still []


From the documentation of hash.keys:

Returns a new array populated with the keys from this hash. See also Hash#values.

So the class is Array because the return value is an array.

About your question "Are the keys in a Hash considered an Array unto themselves?", they "kind" of are, hashes in Ruby are implemented as struct (st_table) which contains a list of pointers to each of its entries(st_table_entry),the st_table_entry contains the key and its value, so I guess what the keys method does is just transversing that list taking out each of the keys.

You can read this article of Ilya Grigorik where he explains much better Hashes in Ruby http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/


Do you think there's something paradoxical about this? Keep in mind that hashes aren't arrays in Ruby.

0

精彩评论

暂无评论...
验证码 换一张
取 消