Skip to content

Array#compact does not drop None despite None#nil? == true #45

Description

@lutzcc1

Summary

None#nil? answers true — documented in #25 as a deliberate compromise so that "AR internals and ordinary nil checks treat an absent value as absent". But Array#compact, the single most common nil-dropping idiom in Ruby, does not drop it:

[Some(1), None()].compact          # => [Some(1), None]      expected [Some(1)]
[Some(1), None()].flat_map(&:to_a) # => [1]                  the working idiom

Tested on errgonomic 0.8.0.

Cause

Array#compact is implemented in C and tests for the actual Qnil object rather than calling nil?. So the None#nil? == true compromise, which is what makes ordinary nil checks work, stops short exactly where a collection is involved.

Why it matters

This is silent, and it lands on a documented convention. In our Rails app the action-tree layer's README teaches this exact shape for declaring sub-actions:

def all_actions
  [
    pod_provision_action,
    cluster_update_route_action,
    pod_health_check_action
  ].compact
end

Those are all optional: true belongs_to, so under ActiveRecordOptional every one becomes an Option and .compact silently keeps the Nones. Downstream consumers then dereference them:

  • a recursive step collector guarded by return [] unless actionNone is truthy, so the guard passes and action.steps raises
  • a tree-printer doing all_actions.map { |a| a.examine(prefix) } — unguarded, raises

9+ models in our codebase use .compact in exactly this position, so this will recur on nearly every action model we convert.

The asymmetry is the trap: if x.nil?, unless x.nil?, and x.nil? ? a : b all behave as #25 promises. [..].compact looks like the same check and does not.

Suggested fix

I don't think this is fixable in Array#compact itself without patching core, and patching Array#compact globally would be a much larger blast radius than this is worth.

Two things that would help instead:

  1. Document it alongside the None#nil? compromise in Document the ActiveRecord pragmatic compromises in ActiveRecordOptional #25 — the compromise's stated purpose is "ordinary nil checks keep working", and it's worth naming the one very common check where that isn't true, with flat_map(&:to_a) as the replacement.
  2. Consider Array#compact_options (or similar) in the core_ext set added by Optional collections: OptionalHash, OptionalArray, and additive lookups #38, so there's a named idiom to reach for rather than the somewhat cryptic flat_map(&:to_a).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions