Skip to content

Instantly share code, notes, and snippets.

@phlipper
Created April 2, 2015 15:02
Show Gist options
  • Save phlipper/ded40bd9289307adb19c to your computer and use it in GitHub Desktop.
Save phlipper/ded40bd9289307adb19c to your computer and use it in GitHub Desktop.
TECH603 Day 3 - Working with functions
a, b = "a", "b"
c = "c"
d = "d"
e = "e"
f = "f"
# define it - ugly style
def function0(arg0, arg1, arg2, arg3, arg4, arg5)
puts "you passed in #{arg0}, #{arg1}, #{arg2}, #{arg3}, #{arg4}, and #{arg5}"
end
# call it
function0(a, b, c, d, e, f)
# let's use an array instead of an ugly list of args
def function1(array)
puts "you passed in #{array}"
end
function1([a, b, c, d, e, f])
# let's do a special thing - splatting! yay
def function2(*args)
puts args.class
puts "you passed in #{args}"
end
function2(a, b, c, d, e, f)
function2(a)
# look ma, no parens!
def increment number, step = 1
puts number + step
end
increment 1, 1
increment 5, 5
increment 2
def increment(number, step = 1)
puts number + step
end
increment(1, 1)
increment(5, 5)
increment(2)
# keyword
def keyword_args(arg0:, arg1:, arg2:, arg3:, arg4:, arg5:)
puts "you passed in #{arg0}, #{arg1}, #{arg2}, #{arg3}, #{arg4}, and #{arg5}"
end
keyword_args(arg1: b, arg2: c, arg3: d, arg4: e, arg5: f, arg0: a)
# using a hash <- old school
def address_with_hash(address_hash)
puts "#{address_hash["name"]} #{address_hash["street"]}"
end
# with keyword args... and a double splat!
def address(name:, street:, city:, state: "NV", zip:, **kwargs)
puts "#{name} #{street} #{state}"
puts "kwargs: #{kwargs}"
end
address("Don Morrison", "123 Street", "Springfield", "NV", "12345")
def address(**kwargs)
puts "kwargs: #{kwargs}"
end
address(
foo: "bar",
zip: "12345",
name: "Don Morrison",
street: "123 Sesame Street",
city: "Springfield",
state: "NV",
country: "USA"
)
# increment using kwargs
def inc(number, by: 1)
puts number + by
end
inc(1, by: 1)
inc(5, by: 5)
inc(2)
def join_words(*words)
first = words[0...-1].join(", ")
last = words[-1]
puts "you passed in #{first}, and #{last}"
end
join_words("one", "two")
join_words("one", "two", "three", "four")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment