Code & Clay – Notes to self. Mainly Ruby/Rails.

Hash#to_proc

In Ruby, we can convert hashes to procs.

> {}.respond_to?(:to_proc)
=> true

> {}.to_proc
=> #<Proc:0x000000010741f7a0 (lambda)>

We could do something like this.

my_hash = {
  1 => "thumb",
  2 => "shoe",
  3 => "knee"
}

> [*1..3].map(&my_hash)
=> ["thumb", "shoe", "knee"]

The hash is called with each element of the array.

If an element in the array does not correspond with a key in the hash, it maps to nil.

> [*1..4].map(&my_hash)
=> ["thumb", "shoe", "knee", nil]