breaking into the unknown…

arguments in ruby

Leave a comment

In this post we will look into arguments in ruby. arguments are the values a method expecting when the method is called. The number of values to be passed and its type is fixed at the time of method definition and is called parameter list.

Parameter : They are variables associated with method at the time of defining it. It decides the number of values and its type which need to be passed at the time a method is called. Each parameter name must be unique in the parameter list.Parameters are positional: they describe the argument in the corresponding position of the argument list. The correspondence isn’t one‐to‐one, as we will see below, but each parameter consumes as many arguments as it can, leaving those that remain for the following parameters.

Arguments : The values passed to the method when it is called. They need to be passed according to the parameter list

To discuss various type of arguments, let create argument_demo.rb file and call different methods in the ruby console.

class ArgumentDemo
  # in ruby argument are passed by reference rather then value
  def demo_pass_by_referance(ref_var)
    substituted_val = ref_var.gsub!("a", "1")
    puts substituted_val

  # in ruby you do not need to define the type of parameter 
  # i,e int, string get defined dynamically by ruby based 
  # on the passed value at time of method call
  # NOTE: ruby is a dynamically typed language

  def i_need_required_argument(house, street, city, post)
    puts "I exactly need 4 arguments"

  #default value is provided in the start
  def start_with_default(house =12, street ="gandhi road", city, post)
    puts "house => #{house} ,street => #{street}, city => #{city}, post => #{post}"

  # default value is provided at the end
  def end_with_default(house, street, city = "UP", post = 122341)
    puts "house => #{house}, street => #{street}, city => #{city}, post => #{post}"

  # method with any number of arguments
  def variable_arguments(*args)
    args.each do |arg|
      puts arg

  # argument as key => value pair
  def named_arguments(args = {})
    puts args[:house]
    puts args[:street]

  # method supporting block argument
  def block_arguments(any_value)
    if block_given?
      raise "You must pass a block"


Let us load the above file on irb and try out calling different methods with different type of argument

$irb #open irb
> load “/home/arun/Desktop/argument_demo.rb” #load the file

Before we read about different types of argument, we should understand that in ruby the arguments are always passed by reference not the value. It means that if the argument get modified by the method, its actual value also get modified. See the below output on the console

> my_name = “arun” 
=> “arun”
> @argumnets =
=> #<ArgumentDemo:0x9b15400>
> @argumnets.demo_pass_by_referance(my_name)
1.9.3p194 :011 > my_name
=> “1run”

So you can see that you have set the variable my_name with value arun. You passed the my_name variable as a argument to method demo_pass_by_referance, which modify the variable my_name inside it. But when you go outside the method and again try to see the value of my name, you see that now my_name is containing the modified value. This show that, here the my_name is not containing value arun but a reference to this value, so any modification on my_name actually change the referred value.

NOTE  : never modify any variable passed as argument to any method directly, specially if it is also passed to other method . I can give a real case example in terms of params. params in rails store all the values passed with a request to a controller and is accessible throughout the controllers and used to pass as argument to many of the controller methods. Once I did the above things i,e params[:auth_token].gsub!(“_”, “-“) in one of my method and it break the whole authentication system of  my application as the above line corrupt the token which is referenced by many other methods. So whenever you want to modify any argument in a method perform the action on duplicate copy of the argument i,e using dup. So using params[:auth_token].dup.gsub!(“_”, “-“) will not change the referenced value as the operation is performed on the copy of argument.

With the above discussion, Now ,We will experiment with arguments by calling different methods in above file on irb console.

1 => Required Argument :

  1. These are the argument which must be passed when the method is called
  2. passing lesser number of argument as defined in parameter list will throw argument error
  3. nil and false are as valid an argument as any other. If a method requires an argument and nil is supplied in its place, Ruby will not complain. Methods wishing to prohibit such values must do so themselves.

See the below output on irb console

> @arg_demo =
=> #<ArgumentDemo:0xa276320>
> @arg_demo.i_need_required_argument(12, “chandni chowk”, “Delhi”, 11106)
I exactly need 4 arguments
> @arg_demo.i_need_required_argument(12, “chandni chowk”, “Delhi”)
ArgumentError: wrong number of arguments (3 for 4)
> @arg_demo.i_need_required_argument(12, “chandni chowk”, false, nil)
I exactly need 4 arguments

2 => Optional Argument

  1. If the parameter are given default value, it become optional i,e the method will not complain if the corresponding argument is not passed.Say if a method have 4 parameter and 2 are given default value then argument error will occur if you pass less then 2 or more then 4 argument.
  2. If default value is passed to parameters,  all the default value should be either from start or towards the end. if you put the default value in between, it will give syntax error when the file is loaded or compiled
  3. If no of passed argument is equal to the no of parameter, all the default values will be overridden.
  4. When default parameters are defined towards the end, the passed arguments are assigned to them following the know convention i,e left to right, say the method have 4 parameters in which last two have default value and you pass 3 argument, then these argument is set to first 3 i,e default value of 3rd will be overridden and only the 4th parameter will have the default value
  5. When you set the default parameter at the beginning, it create confusion in assignment of argument to them as far as I have understand.This is how they are getting assigned. Non default parameter are assigned right to left, the remaining arguments are now assigned to the default parameter from left to right as usual.

Below output can illustrate the above points

> @argumnets =
=> #<ArgumentDemo:0x8988a70>
> @argumnets.start_with_default(“UP”,”2342″) # two argument passed
house => 12 ,street => gandhi road, city => UP, post => 2342  #assigned to the last two non default parameter

> @argumnets.start_with_default(“my street”,”UP”,”2342″) # 3 argument passed
house => my street ,street => gandhi road, city => UP, post => 2342 # last 2 i,e “UP”,”2342″ assigned to city and post following right to left rule and the remaining one i,e “my street” is assigned to the first parameter house following left to right rule

> @argumnets.start_with_default(32,”my street”,”UP”,”2342″) # 4 argument passed so assigned as usual following left to right rule , infact if no of passed argument is equal to the number of parameter bot rule i,e left to right or right to left will give same result
house => 32 ,street => my street, city => UP, post => 2342

> @argumnets.end_with_default(32, “my_street”) # 2 argument passed
house => 32, street => my_street, city => UP, post => 122341 # first two are assigned following left to right rule

> @argumnets.end_with_default(32, “my_street”, “Patna”) # 3 argument are passed
house => 32, street => my_street, city => Patna, post => 122341 # first 3 are assigned following left to right rule

> @argumnets.end_with_default(32, “my_street”, “Patna”, “5643”) # 4 argument are passed
house => 32, street => my_street, city => Patna, post => 5643 # first 4 are assigned following left to right rule

NOTE : Always keep the parameter with default value towards the end

3 => Variable list Arguments

  1. They are created by defining single parameter preceded by * . They are also known as spat arguments
  2. Any number of arguments can be passed separated by comma
  3. In the method they are available as an array

Below output can illustrate the above point.

> @argumnets =
=> #<ArgumentDemo:0x89d1784>
> @argumnets.variable_arguments(1, “arun”, 3)
> @argumnets.variable_arguments(1, “arun”, 3, “kapil”)

4 => Named Arguments

  1. They are defined as a hash with argument being passed as key => value pair
  2. The advantage is that These arguments are not positional thus you do not need to remember to pass a particular value at particular position.
  3. It support variable list argument i,e you can pass any number of arguments.
  4. Disadvantage is that it do not give argument error if user pass no or wrong number of argument. It has to be handle by you in the code.

1.9.3p194 :048 > @argumnets =
=> #<ArgumentDemo:0x8a44018>
1.9.3p194 :050 > @argumnets.named_arguments({:house =>12, :street => “xyz street”})
xyz street

5 => Block Arguments

  1. They are defined by putting & before the parameter name . It has to defined after defining all other parameters including the default one
  2. While calling the method, you should pass the block argument after closing parenthesis of the arguments i,e method(arg1, arg2..){}
  3. They do not contributes to argument count , so No argument error is thrown. You can check it with block_given? method and raise exception to user for passing the block
  4. Block arguments are used in method with yield keyword . read more about block in this post.

> @argumnets =
=> #<ArgumentDemo:0x8a5e6ac>
1.9.3p194 :066 > @argumnets.block_arguments()
ArgumentError: wrong number of arguments (0 for 1)
> @argumnets.block_arguments(232){puts “Iam passed as a block”}
Iam passed as a block
> @argumnets.block_arguments(232)
RuntimeError: You must pass a block

=> Arity
The arity of a method is the number of arguments it takes. If the method expects a fixed number of arguments, this number is its arity. If the method expects a variable number of arguments, its arity is the additive inverse of its parameter count. Methods implemented in C, i.e. most core methods, have an arity of -1 if they accept a variable number of parameters. It follows, then, that an arity ≥ 0 indicates a fixed number of parameters; a negative value, a variable number. Method and Proc objects have #arity methods which return the arity for the method/proc it objectifies.

Classification by Arity

Methods with fixed arities can be classified as follows: A unary method expects exactly one operand (its receiver), a binary method requires two (its receiver and one argument), ternary-method requires exactly three (its receiver and two arguments), an n-ary method requires n operands (its receiver, and n-1 arguments).

Author: arunyadav4u

over 7 years experience in web development with Ruby on Rails.Involved in all stage of development lifecycle : requirement gathering, planing, coding, deployment & Knowledge transfer. I can adept to any situation, mixup very easily with people & can be a great friend.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s