« Back to Index

Ruby Splat (single and double)

View original Gist on GitHub

Ruby Splats.rb

# 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}]