Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to send a Hash as an argument to a function in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 165
    Comment on it


    In Ruby it is possible to send a Hash as an argument to a method.

    Suppose we have a method named conversion_method which has 4 default parameters(a,b,c,d). ex:-

    2.1.5 :086 >   def conversion_method(a:10, b:20, c:30, d:40)
    2.1.5 :087?>   puts "a = " + a.to_s + " b = " + b.to_s + " c = " + c.to_s + " d = " + d.to_s
    2.1.5 :088?>   end 
    

    And we have a Hash with 4 key-value pairs , ex:-

    2.1.5 :096 > arguments = { a: 100, b: 200, c: 300, d: 400 }
     => {:a=>100, :b=>200, :c=>300, :d=>400}
    

    You can verify that arguments is a Hash.

    2.1.5 :098 > arguments.class
     => Hash
    

    Now if we wish to send this Hash to the conversion_method function we can send it as follows

    2.1.5 :100 > conversion_method(**arguments)
    a = 100 b = 200 c = 300 d = 400
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: