読者です 読者をやめる 読者になる 読者になる

What is nil? No matter. What is nil? Never mind.

"What is nil?" is mysterious question in Ruby. You may answer like "nothing", "nothing exists", or "NULL". Brian, the founder of Rubinius, wrote his thoughts around Lonely operator.

CRuby developers sometimes discussed about nil for example [ruby-dev:29374] nil.to_s. The thread is talked about the behavior of nil.to_s.

The use case of &.

Ruby solves real problem. Ruby's complexity is come from the complexity of the real world. When Ruby adds a new feature, it should be designed for real use case. For example Lonely operator (and the ancestor Object#try! of ActionSupport) are designed for below:

<% if current_user && current_user.premium? %>
  Hi,<%= current_user.name %>, we offer a new campaign!
<% end %>

Rails programmers often write a template like this. In this case, current_user is nil when the user is not login yet; it's actually valid status.

Some people try to define NilClass#method_missing like Brian says. "The Hopelessly Egocentric Blog Post" is a good article about the idea. I summarize the article: don't try it. Rails developed Object#try/try! from the experience. Ruby agreed the conclusion and added &..

The use case of dig

The use case of Hash#dig and Array#dig is JSON from REST API. For example following Redmine's REST API (full result),

{
    "issue": {
        "id": 11537,
...
        "assigned_to": {
            "id": 13,
            "name": "Yukihiro Matsumoto"
        },
        "subject": "Introduce \"Safe navigation operator\"",
        "done_ratio": 100,
        "created_on": "2015-09-18T09:29:09Z",
        "updated_on": "2015-12-05T07:58:25Z",
        "closed_on": "2015-12-05T07:58:25Z"
    }
}

You can get matz by json.dig('issue', 'assigned_to', 'name') without suffering issue doesn't exist or it is not assigned anyone.

Traceable nils

I don't have a use case for this because I don't have an experience suffered to explore where a nil come from. When I hit "NoMethodError: undefined method `...' for nil:NilClass", it usually come from models. It doesn't need to trace. Or if people hit a trouble the issue is how the nil come from, not where the nil is born, I imagine. Anyway such experiment is interesting. I watch the reaction by developers.