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!

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!

Enjoy!

Twitter

Total
5
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
what-is-a-kpi?-how-to-choose-the-best-kpis-for-your-business

What is a KPI? How To Choose the Best KPIs for Your Business

Next Post
building-a-beautiful-kanban-board-with-node.js,-react-and-websockets-

Building a beautiful Kanban board with Node.js, React and Websockets 🦄 ✨

Related Posts