Last active
June 13, 2016 10:41
-
-
Save joecorcoran/098cd81a2736fbeb4ffcefe413d2cb5a to your computer and use it in GitHub Desktop.
Ruby keyword argument fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# A weird quirk of keyword args in Ruby that just tripped me up. | |
# An object passed as the second argument here will be used | |
# differently depending on its type. | |
def test(a, b = [], **c) | |
[a, b, c] | |
end | |
# As expected, the default values work. | |
test(:one) # => [:one, [], {}] | |
test(:one, :two) # => [:one, :two, {}] | |
# But if the second arg is a hash, Ruby assumes we want to | |
# use it as the splatted keyword args. This feels odd to me. | |
test(:one, {}) # => [:one, [], {}] | |
# Even more confusing is that if Ruby thinks the second argument | |
# can be coerced into a hash, we get this mess... | |
class Foo | |
def to_hash | |
:oh_dear | |
end | |
end | |
test(:one, Foo.new) # => TypeError: can't convert Foo to Hash (Foo#to_hash gives Symbol) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment