Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created July 31, 2021 03:48
Show Gist options
  • Save JoshCheek/fff56835d784cae1d7cb282fedef0646 to your computer and use it in GitHub Desktop.
Save JoshCheek/fff56835d784cae1d7cb282fedef0646 to your computer and use it in GitHub Desktop.
Ruby 2 & 3's keyword args and how `ruby2_keywords` works
# Helpers to make the code below easier to read
class Array
def keywords?() = Hash.ruby2_keywords_hash?(self[-1])
def to_keywords!() = (self[-1] = Hash.ruby2_keywords_hash(self[-1]))
end
# Code to facilitate the examples below
def record_args(*args) = args
def call_this(val:) = val
args = record_args val: 123 # => [{:val=>123}]
# It's a normal hash, Ruby won't pass it into the keywords slot
args.keywords? # => false
call_this *args rescue $! # => #<ArgumentError: wrong number of arguments (given 1, expected 0; required keyword: val)>
# We can explicitly turn it into a keywords hash
call_this *args rescue $! # => #<ArgumentError: wrong number of arguments (given 1, expected 0; required keyword: val)>
args.to_keywords!
call_this *args # => 123
# `ruby2_keywords` modifies the method to implicitly do what we did above
record_args(val: 1).keywords? # => false
ruby2_keywords :record_args
record_args(val: 1).keywords? # => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment