Working with Ruby there are times you want a method to have required arguments without chaining multiple if else
statements
A simpler and easy way to handle required arguments is,
# define a method with named arguments like this results in an
# error when name is not provided
def greetGuest(name:)
puts "Welcome #{name}!"
end
# invoking method without name will throw ArgumentError
greetGuest # ArgumentError: missing keyword: name
greetGuest(name: "Salley" ) # Welcome Salley!
And even better you can have default arguments like:
def greetGuest(name: "Anonymous Guest")
puts "Welcome #{name}!"
end
# invoking method without name will use the default argument
greetGuest # Welcome Anonymous Guest!
Top comments (0)