4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

to_proc hack to access hash

Last updated at Posted at 2014-11-17
class Array
  def to_proc
    ->(h) { length == 1 ? h[first] : h.values_at(*self) }
  end
end
[
  { name: "Ruby", "age" => 21 }, { name: "Common Lisp", "age" => 56 }
].map(&[:name, "age"])

# => [["Ruby", 21], ["Common Lisp", 56]]

But it is about 2.7 times slower than built-in way of doing this:

require 'benchmark/ips'

class Array
  def to_proc
    ->(h) { length == 1 ? h[first] : h.values_at(*self) }
  end
end

LANGUAGE_AND_AGE = [
  { name: "Ruby", "age" => 21 }, { name: "Common Lisp", "age" => 56 }
]

def built_in
  LANGUAGE_AND_AGE.map { |h| [h[:name], h['age']] }
end

def to_proc_hack
  LANGUAGE_AND_AGE.map(&[:name, "age"])
end

Benchmark.ips do |x|
  x.report('built_in')     { built_in }
  x.report('to_proc_hack') { to_proc_hack }
  x.compare!
end
$ ruby -v to-proc-hack.rb
ruby 2.2.0preview1 (2014-09-17 trunk 47616) [x86_64-darwin13]

Calculating -------------------------------------
            built_in     88340 i/100ms
        to_proc_hack     47669 i/100ms
-------------------------------------------------
            built_in  1806140.9 (±6.2%) i/s -    9010680 in   5.009917s
        to_proc_hack   665738.9 (±4.9%) i/s -    3336830 in   5.024990s

Comparison:
            built_in:  1806140.9 i/s
        to_proc_hack:   665738.9 i/s - 2.71x slower

Source: Array#to_proc for hash access - The Pug Automatic

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?