DEV Community

Cover image for Ruby require argument keyword
Code Salley
Code Salley

Posted on

Ruby require argument keyword

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!

Enter fullscreen mode Exit fullscreen mode
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!
Enter fullscreen mode Exit fullscreen mode
Enjoy!
Twitter

Top comments (0)