Skip to content

Instantly share code, notes, and snippets.

@sowenjub
Last active February 24, 2021 19:12
Show Gist options
  • Save sowenjub/a0357d9154fb9ec2a51879edb9350af0 to your computer and use it in GitHub Desktop.
Save sowenjub/a0357d9154fb9ec2a51879edb9350af0 to your computer and use it in GitHub Desktop.
Some notes about the splat operator
def args_to_array(*args)
p args
end
args_to_array("hello", "world")
# ["hello", "world"]
def args_to_array(foo, *args) # Works, order matters
p "foo: #{foo}", args
end
args_to_array("hello", "world")
# "foo: hello"
# ["world"]
a, *b, c = 1, 2, 3, 4, 5
p a, b, c
# 1
# [2, 3, 4]
# 5
# same as
def args_to_array(a, *args, c) # args can be in the middle
p a, args, c
end
args_to_array(1, 2, 3, 4, 5)
def args_to_array(foo: :bar, *args) # Fails, incompatible with keyword arguments
p foo, args
end
args_to_array("hello", "world")
# syntax error, unexpected *
def options_to_hash(foo: :bar, **options)
p foo, options
end
options_to_hash(foo: 1, some_option: true)
options_to_hash(some_option: true, foo: 1) # Order doesn't matter
# 1
# {:some_option=>true}
def options_to_hash(foo:, **options, bar:) # No can do
p foo, options, bar
end
options_to_hash(some_option: true, bar: 2, foo: 1)
# syntax error, unexpected tLABEL, expecting & or '&'
def add(a, b)
a + b
end
add(1, 2) # 3
add(*[1, 2]) # 3
add([1, 2]) # wrong number of arguments (given 1, expected 2)
def add(*numbers)
numbers.sum
end
p add(1, 2) # 3
p add(*[1, 2]) # 3
p add([1, 2]) # Array can't be coerced into Integer
h1 = { a: 1, b: "2" }
h2 = { c: 3, a: 4, **h1 }
p h2
# {:c=>3, :a=>1, :b=>"2"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment