Project

General

Profile

Actions

Feature #18959

closed

Handle gracefully nil kwargs eg. **nil

Feature #18959: Handle gracefully nil kwargs eg. **nil

Added by LevLukomskyi (Lev Lukomskyi) almost 4 years ago. Updated 29 days ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:109449]

Description

The issue:

def qwe(a: 1) end

qwe(**nil) #=> fails with `no implicit conversion of nil into Hash (TypeError)` error

{ a:1, **nil } #=>  fails with `no implicit conversion of nil into Hash (TypeError)` error

Reasoning:

I found myself that I often want to insert a key/value to hash if a certain condition is met, and it's very convenient to do this inside hash syntax, eg.:

{
  some: 'value',
  **({ id: id } if id.present?),
}

Such syntax is much more readable than:

h = { some: 'value' }
h[:id] = id if id.present?
h

Yes, it's possible to write like this:

{
  some: 'value',
  **(id.present? ? { id: id } : {}),
}

but it adds unnecessary boilerplate noise.

I enjoy writing something like this in ruby on rails:

content_tag :div, class: [*('is-hero' if hero), *('is-search-page' if search_page)].presence

If no conditions are met then the array is empty, then converted to nil by presence, and class attribute is not rendered if it's nil. It's short and so convenient! There should be a similar way for hashes!

I found this issue here: https://bugs.ruby-lang.org/issues/8507 where "consistency" thing is discussed. While consistency is the right thing to do, I think the main point here is to have fun with programming, and being able to write stuff in a concise and readable way.

Please, add this small feature to the language, that'd be so wonderful! 🙏


Related issues 1 (0 open1 closed)

Related to Ruby - Bug #20064: Inconsistent behavior between array splat *nil and hash splat **nilClosedActions
Actions

Also available in: PDF Atom