Default values and Hash parameters

I had talked before about it. We can use a hash to pass parameter to our method, and que can merge with another hash that contain the defaults values. Why to do that :

  • Set Default Values in Methods : Avoid unexpected behaviour.
  • Simple Hash as Default Method Parameter : This form allows you to add functionality to methods without breaking existing calls
def add_book(p_arg)

  p_arg = {:title=>"no title", 
           :author=>"anonymous",
           :language=>"esperanto"}.merge! p_arg

end
add_book :title=>"El Qujote",
         :author=>"Miguel De Cervantes",
         :language=>"spanish"

=> {:language=>"spanish", :title=>"El Qujote", :author=>"Miguel De Cervantes"}
add_book :title=>"El Qujote",
         :author=>"Miguel De Cervantes"

=> {:language=>"esperanto", :title=>"El Qujote", :author=>"Miguel De Cervantes"}
add_book :title=>"El Qujote",
         :author=>"Miguel De Cervantes"
         :foo=>:bar

=> {:language=>"esperanto", :foo=>"bar" ,:title=>"El Qujote", :author=>"Miguel De Cervantes"}

No Comment

No comments yet

Leave a reply