Types of arguments in Ruby | Parameters in Ruby

 


In Ruby, arguments can be classified into several types based on how they are passed to the methods. Let's see each argument type with an example:

1. Required arguments:

  • This argument must be provided when calling a method, otherwise, it will throw the argument error.

    def greet(name, country)
        puts "My name is  #{name} and I am from #{country}"
    end
    greet("Yash", "India")

  • If we pass only one argument it will throw the below error 
        `greet': wrong number of arguments (given 1, expected 2) (ArgumentError)

2. Default arguments:

  • Default arguments have predefined values that will be used when no arguments are passed to the method.
    def greet(name="Yash")
        puts "My name is  #{name} "
    end
    greet

3. Variable arguments:

  • They allow a method to accept a variable number of arguments. This argument is also known as the splat argument.
    def total(*num)
        puts num.sum
    end
    total(1, 2, 3)

4. Keywords Arguments:

  • These arguments are passed by name, order doesn't matter it provides more flexibility and clarity.
     def greet(name: , country: )
      puts "My name is #{name} and i am from #{country}"
  end  
  greet(country: "India", name: "Yash")


5. Block Arguments:

  • In Ruby, the method can also accept the block. A block of code is passed in the method as an argument. Block is passed implicitly using the yield keyword or explicitly using the &block keyword.
    def greet
      yield("Yash")
  end
  greet { |name| puts "Hello #{name}"}

    OR

  def greet(&block)
      block.call("Yash")
  end
  greet { |name| puts "Hello #{name}"}


These are the main types of arguments each serving a different purpose and providing flexibility.

Comments