From: "LevLukomskyi (Lev Lukomskyi)" Date: 2022-08-26T20:43:53+00:00 Subject: [ruby-core:109719] [Ruby master Feature#18959] Handle gracefully nil kwargs eg. **nil Issue #18959 has been updated by LevLukomskyi (Lev Lukomskyi). Currently: ```ruby "xyz".sub(/y/, nil) #=> TypeError: no implicit conversion of nil into String def nil.to_hash; {} end "xyz".sub(/y/, nil) #=> "xz" ``` Ok, the behavior is different, but it doesn't mean that we cannot implement the feature, it just means **that ruby should implement better `nil` handling in `sub` method**, and instead of raising `TypeError` it should raise `ArgumentError` if `nil` is passed, which is more expected than just silently remove an occurrence, and also describe this in [docs](https://ruby-doc.org/core-3.1.2/String.html#class-String-label-Substitution+Methods) since currently, it says that the second parameter can be either string, hash, or block. If `sub` method is fixed this way then there will be no compatibility issues. @austin your latest example has 110 symbols, the condition should be duplicated for each new hash key, as well as the ternary operator, so it's not good. Previous example has 294 symbols ��� it'll need more tests, because more code == more bugs and maintenance efforts. ---------------------------------------- Feature #18959: Handle gracefully nil kwargs eg. **nil https://bugs.ruby-lang.org/issues/18959#change-98953 * 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: