[ruby-core:109676] [Ruby master Feature#18959] Handle gracefully nil kwargs eg. **nil
From:
"sawa (Tsuyoshi Sawada)" <noreply@...>
Date:
2022-08-25 03:47:58 UTC
List:
ruby-core #109676
Issue #18959 has been updated by sawa (Tsuyoshi Sawada).
LevLukomskyi (Lev Lukomskyi) wrote in #note-8:
> 2. => more specifically `.tap(&:compact!)` since `compact!` may return `nil` if nothing changed.
I think `tap(&:foo)` is actually not that much efficient, and `tap(&:compact!)` could be slower than using `compact`. I meant to simply use `compact!` in a different statement, not in a chain.
> 3. there might be also a case when you want to merge another hash under some conditions, eg.:
>
> ```ruby
> {
> some: 'value',
> **({ id: id, name: name } if id.present?),
> }
> ```
If you want to handle the whole subhash as one item, I think you should move that outside of the hash:
```ruby
foo = {
some: 'value',
}
foo.merge!({id: id, name: name} if id.present?
```
----------------------------------------
Feature #18959: Handle gracefully nil kwargs eg. **nil
https://bugs.ruby-lang.org/issues/18959#change-98900
* Author: LevLukomskyi (Lev Lukomskyi)
* Status: Open
* Priority: Normal
----------------------------------------
The issue:
```ruby
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.:
```ruby
{
some: 'value',
**({ id: id } if id.present?),
}
```
Such syntax is much more readable than:
```ruby
h = { some: 'value' }
h[:id] = id if id.present?
h
```
Yes, it's possible to write like this:
```ruby
{
some: 'value',
**(id.present? ? { id: id } : {}),
}
```
but it adds unnecessary boilerplate noise.
I enjoy writing something like this in ruby on rails:
```ruby
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!
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>