Various methods defined on NilClass are handy to avoid Method undefined on NilClass errors, and frees you from using try, oror, andand, ||, && in various occasions:
-
to_a for multiple dimensioned array when there might not be some values for some indices:
array[i].to_a[j].to_a[k]
-
to_s pattern match that might fail:
string[regex].to_s*2
-
to_i, to_f, to_c for index search that might fail, etc:
array.index(element).to_i*3
But there is no NilClass#to_hash although there is Hash#to_hash.
If such method existed (class NilClass; def to_hash; {} end end), then we would be able to do:
- to_hash for multiple embedded hash when there might not be some values for some keys:
hash[:a].to_hash[:b].to_hash[:c]
The best alternative I can think of is:
hash.fetch(:a, {}).fetch(:b, {})[:c]
but it would be nice if we had NilClass#to_hash. Why is it missing?
Edited
I sent a request about
NilClass#to_hashto ruby development. Matz rejected it shortly. Andrew notified me in the comment below that Matz gave a comment to it. Answer to the question is thus given my Matz, and you can see that by following Andrew’s link below.