JetRockets profile image JetRockets

Simple way to get all values from hash

twitter logo github logo ・1 min read

In the ruby from the box, we can't find all the hash values if it's nested.
I suggest an easy way to find all the values using recursion.

Example hash:

hash = {
  a: 2,
  b: { c: 3, d: 4, e: {f: 5}}
}
> hash.values
=> [2, {:c=>3, :d=>4, :e=>{:f=>5}}]

That's not an option, we need all the values.

def deep_values(array = [], object:)
  object.each do |_key, value|
    if value.is_a?(Hash)
      deep_values(array, object: value)
    else
      array << value
    end
  end
  array
end

> deep_values(object: hash)
=> [2, 3, 4, 5]

If you run the benchmark with this data, we get the following data:

>  puts Benchmark.measure { 100_000.times { hash.values } }
=> 0.028920   0.002643   0.031563 (  0.032759)

>  puts Benchmark.measure { 100_000.times { deep_values(object: hash ) } }
=> 0.140439   0.003318   0.143757 (  0.146637)
twitter logo DISCUSS (1)
JetRockets is a technology consulting firm that architects, designs, develops and supports enterprise-level web, mobile and software platforms helping clients achieve their goals and grow their businesses.
Classic DEV Post from Dec 18 '18

Stop trying to be so DRY, instead Write Everything Twice (WET)

Write everything twice, just not a third time.