Ruby method parameters

Tram Ho


When working with method in ruby , you may encounter cases where the parameters defined in the method will be of the form: *args , **kwargs , &block , … So what are they, today we will find Understand this issue via the ruby method parameters

?


Default parameters

  • When defining a method , we can specify a default value for them. When a method is called, if the arguments values ​​are less than the previously declared parameters values ​​then the default parameters will use those default assigned values.
  • If there is more than one default parameter in the method definition, these parameters must be contiguous. For example, it is not possible to put another parameter between the two default parameter .
  • method has more than one default parameter when executed with a list of arguments passed in, these arguments will be valued for the default parameters from left to right:

Parameter with splat operator (*)

  • The array type parameter marked with the * in front is used when passing an array of any arguments:
  • A method has no more than one parameter of this type, an array type parameter must be adjacent to the default parameters, and may precede other normal parameters:
  • Additionally, * also used when we want to pass an array of arguments when we call the method :


Mapping arguments to parameters

We will learn how ruby assigns arguments passed to the parameters defined in the method .

Suppose a method has o original parameters (normal parameters), d parameters are assigned default values, and 1 parameters are array type. method is called with a argument, then:

  • If a < o : an ArgumentError occurs
  • If o <= a <= o+d : ao default parameter will be assigned value, the rest, o+da default parameter will use the original default value.
  • If a > o+d : aod the aod argument will be assigned to the last array parameter

Using hash for named arguments

When a method requires more than 2 or 3 parameters, it is very difficult to execute this method , we need to remember the order of all these parameters when passing the arguments. To solve this problem, in ruby we can use the hash argument :

  • If in the method the hash is at the end (or is followed by a block ), we can omit the {} sign when calling the method :

Parameter with double splat (**) operator

One more way to declare a parameter of type hash: use ** :


Block arguments with (&)

  • A block may be passed when calling the method :

    If in the parameter list there is no & , the block can still be passed via {} or do; ;end
  • Note that the parameter with & is defined only once, and it must be placed at the bottom of the list:


Share the news now

Source : Viblo