Home > Mobile >  How to make parameters flexible in ruby?
How to make parameters flexible in ruby?

Time:09-17

Im pretty new to ruby . I have a method lets say -" method_X " with parameters (client_name, client_dob).

def method_X client_name, client_dob

(BODY OF THE METHOD)

end

Now I want to introduce a third parameter let's say "client_age". I want my method_X to have a flexibility in taking the parameters.I'm getting an error to mandatorily enter client_name if I forget. I should have flexibility to not mandatorily enter all the three parameters as input. How can I achieve this? Thank you in advance!

CodePudding user response:

In Ruby, you can declare parameters as required, default and optional arguments.

  1. required - required parameters need to be passed otherwise it throws an error.

    Ex: def method_X(client_name)

    In this, you need to send the client_name argument, else it throws an error.

  2. default - default parameters are optional arguments, but you should declare the default value for the given parameter while defining the method. So that you can skip the argument if you want or you can send a new value while calling the method.

    Ex: def method_X(client_name="Abc Company")

    In this case, if you haven't passed the client_name argument for the method, the default will be Abc Company. You can default to any value you like, say nil, empty string, array etc.

  3. optional - Optional parameters where you need to use the splat(*) operator to declare it. This operator converts any number of arguments into an array, thus you can use it if you don't how many arguments you will pass. If no arguments, it gives an empty array.

    Ex: def method_X(*client_name)

  • Related