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


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]

If you really want to get to grips with Ruby development and gain a solid understanding of Object Oriented Design, I thoroughly recommend Sandi Metz's Practical Object Oriented Design in Ruby. It's the perfect introduction to OOP and pragmatic Ruby. You can buy it here.

“Meticulously pragmatic and exquisitely articulate, Practical Object Oriented Design in Ruby makes otherwise elusive knowledge available to an audience which desperately needs it. The prescriptions are appropriate both as rules for novices and as guidelines for experienced professionals.”

Katrina Owen, Creator, Exercism

Essential Reading: Learn Rails 6