"foo" ,-6ren">
gpt4 book ai didi

ruby - ruby 中#entries 和#to_a 的区别

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

#entries 之间的基本区别是什么?和 #to_a Enumerable 的方法ruby 中的模块。两者似乎在 Hash 上返回相同的结果

>> hash = {"name" => "foo" , "age" => "23"}
=> {"name"=>"foo", "age"=>"23"}

>> hash.to_a
=> [["name","foo"],["age",23]]

>> hash.entries
=> [["name","foo"],["age",23]]

最佳答案

这是区别(查看 # => 之后的输出):

h = {}
h.method(:entries) # => #<Method: Hash(Enumerable)#entries>
h.method(:to_a) # => #<Method: Hash#to_a>
h.method(:entries).owner # => Enumerable
h.method(:to_a).owner # => Hash

Hash 有一个实例方法 #to_a , 所以它没有调用 Enumerable#to_a .但是 Hash 没有它自己的方法 #entries,所以它调用 Enumerable#entries , 因为 Hash 包含了 Enumerable 模块。

Hash.included_modules # => [Enumerable, Kernel]

Enumerable#entriesEnumerable#to_a 之间没有区别,据我所知,两者使用 TracePoint 的工作方式相似:

1. trace = TracePoint.new do |tp|
2. p [tp.lineno, tp.event, tp.defined_class,tp.method_id]
3. end
4.
5. trace.enable do
6. (1..2).entries
7. (1..2).to_a
8. end

# >> [5, :b_call, nil, nil]
# >> [6, :line, nil, nil]
# >> [6, :line, nil, nil]
# >> [6, :c_call, Enumerable, :entries]
# >> [6, :c_call, Range, :each]
# >> [6, :c_return, Range, :each]
# >> [6, :c_return, Enumerable, :entries]
# >> [7, :line, nil, nil]
# >> [7, :line, nil, nil]
# >> [7, :c_call, Enumerable, :to_a]
# >> [7, :c_call, Range, :each]
# >> [7, :c_return, Range, :each]
# >> [7, :c_return, Enumerable, :to_a]
# >> [8, :b_return, nil, nil]

是的,Hash#to_aEnumerable#to_a 快。

第一部分

require 'benchmark'

class Hash
remove_method :to_a
end

hsh = Hash[*1..1000]


Benchmark.bm(10) do |b|
b.report("Enumerable#to_a") { hsh.to_a }
end
# >> user system total real
# >> Enumerable#to_a 0.000000 0.000000 0.000000 ( 0.000126)

第二部分

require 'benchmark'

hsh = Hash[*1..1000]


Benchmark.bm(10) do |b|
b.report("Hash#to_a") { hsh.to_a }
end
# >> user system total real
# >> Hash#to_a 0.000000 0.000000 0.000000 ( 0.000095)

关于ruby - ruby 中#entries 和#to_a 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20444202/

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