Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between #entries and #to_a in ruby

Tags:

ruby

What's the basic difference between #entries and #to_a methods of Enumerable module in ruby.Both seem to return same result on a Hash

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

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

>> hash.entries
=> [["name","foo"],["age",23]]
like image 831
Varinder Singh Avatar asked Dec 07 '13 17:12

Varinder Singh


1 Answers

Here is the difference(look at the output after # =>):

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 has an instance method #to_a, so it is not calling Enumerable#to_a. But Hash doesn't has it's own method #entries, so it is calling Enumerable#entries, because Hash included Enumerable module.

Hash.included_modules # => [Enumerable, Kernel]

There is no difference between Enumerable#entries and Enumerable#to_a, as far as I can see both are working similar way using 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]

Yes, Hash#to_a is faster than Enumerable#to_a.

Part - I

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)

Part - II

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)
like image 121
Arup Rakshit Avatar answered Sep 22 '22 03:09

Arup Rakshit