DEV Community

Andrey for JetRockets

Posted on • Originally published at jetrockets.pro

4 1

Simple way to get all values from hash

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)

Top comments (1)

Collapse
 
ohaddahan profile image
ohaddahan

Give a try to github.com/evanphx/benchmark-ips for benchmarking.
I believe it's more reliable and accurate.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more