Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method
Hash#to_proc
() -> ^(K) -> V?
to_proc → proc
hash.c
View on GitHub ↗
static VALUE
rb_hash_to_proc(VALUE hash)
{
return rb_func_lambda_new(hash_proc_call, hash, 1, 1);
}
Returns a Proc object that maps a key to its value:
Example
h = {foo: 0, bar: 1, baz: 2} proc = h.to_proc proc.class # => Proc proc.call(:foo) # => 0 proc.call(:bar) # => 1 proc.call(:nosuch) # => nil h.default_proc = proc { |hash, key| "Missing key: #{key}" } # This affect the existing proc object proc.call(:nosuch) # => "Missing key: #{nosuch}"
Related: see Methods for Converting.