Skip to content

Instantly share code, notes, and snippets.

@tjaved573
Last active April 26, 2022 19:28
Show Gist options
  • Save tjaved573/1c11871ffa4d7589f4e2e68d34ed8b51 to your computer and use it in GitHub Desktop.
Save tjaved573/1c11871ffa4d7589f4e2e68d34ed8b51 to your computer and use it in GitHub Desktop.
Ruby Method Arguments
# with this syntax, the order of parameters does not matter
# have to use same name for parameters when passing arguments
#! required and optional arguments are ordered
#! order of passing parameters
#! required => optional => variable => keyword
#! keyword arguments => for more clarity, and removing the need for arguments to be ordered
def method_1(m1:, m2:, m3:)
p m1, m2, m3
end
# method_1(m1:2,m9:3,m2:4)
#! keyword arguments can also be optional with a default value
def method_1(m1:2, m2:, m3:3)
p m1, m2, m3
end
#method_1(m1:20,m3:30,m2:40) # the value for m1 and m2 passed in as argument will be overwritten
#! optional arguments
def testing(a, b=1)
p a,b
end
# testing (23)
#! variable arguments => to capture many arguments as an ARRAY (SPLAT OPERATOR)
def print_all(*args)
p args
end
#print_all(2,3,4,5,6, alpha:"23")
#! variable keyword arguments => to capture many arguments as a HASH (DOUBLE SPLAT OPERATOR)
def print_all(**args)
p args
end
#! *x and **x are both variable arguments
#// if keyword argument is not passed in before variable keyword arguments,
#// the keyword argument will be captured in the variable keyword argument because of the key:value notation
def testing(a, b = 1, *c, d:1, **x)
p a
p b
p c
p d
p x
end
testing('a', 10, 'c', de: 2, alpha:"num", "radon":"noble gas")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment