Last active
October 8, 2015 12:40
-
-
Save Integralist/11207262 to your computer and use it in GitHub Desktop.
Ruby Splat (single and double)
This file contains hidden or 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
# When calling a method with a splat then the parameters are passed as a comma separated list | |
# When receiving arguments with a splat then they are converted into an Array | |
# When using a double splat (2.0+) then the argument is converted into a Hash (i.e. named parameters) | |
def foo(*args) | |
p args | |
end | |
foo 'a', 'b', 'c' | |
# => ["a", "b", "c"] | |
foo *['a', 'b', 'c'] | |
# => ["a", "b", "c"] | |
#################### | |
def bar(a, *b, **c) | |
[a, b, c] | |
end | |
bar 10 | |
# => [10, [], {}] | |
bar 10, 20, 30 | |
# => [10, [20, 30], {}] | |
bar 10, 20, 30, d: 40, e: 50 | |
# => [10, [20, 30], {:d=>40, :e=>50}] | |
bar 10, d: 40, e: 50 | |
# => [10, [], {:d=>40, :e=>50}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment