Using named arguments

Though this looks simple, passing arguments can get complex in real-world Ruby applications because some methods may take a large number of arguments. In such cases, it becomes difficult to know the order of arguments and what values to assign to them.

To avoid this confusion, I like to utilize named arguments, like this:

class ApiConnector
def initialize (title:, description:, url: "google.com")
@title = title
@description = description
@url = url
end

def testing_initializer
puts @title
puts @description
puts @url
end
end

api = ApiConnector.new(title: "My title", description: "My cool description")
api.testing_initializer

You can enter the arguments without having to look at the order in the initialize method. Also, you even change the order of the arguments without causing an error. We can instantiate our class like this:

api = ApiConnector.new(description: "My cool description", title: "My title") 

This instantiation will not change the behavior of the system. If we weren't using named arguments and if we changed the order of the arguments like this, the instance variables would end up being assigned to the opposite values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.16.23